Вопрос

I am working in MVC4 project where i am facing problem with time.Actually my project requirement is to show all time used in application according to Brazil time.So i have used GETUTCDATE() for saving time in application.

Now i want to check if DST is on according to time i saved..i mean central time. How do i check this. I have search on net and found one solution

DECLARE @IsDST BIT;
SET @IsDST = CASE WHEN DateDiff(hour, GetDate(), GetUTCDate()) = 4 THEN 'True' 
             ELSE 'False' END;

SELECT GETDATE() AS GETDATE,
       GETUTCDATE() AS GETUTCDATE,
       @IsDST;

But when i try to run this script,it return false ??

But as per DST calculation,it always starts from 2nd Sunday of March and ends on 1st Sunday of November.

Then it should return true ,that DST is on.

Am i doing right or is there another better approach to check if DST is on central time,so that i can show brazil time according to DST

Это было полезно?

Решение

Well, this particular code doesn't work for detecting DST in Brazil, because it just measures the difference right now between local time and UTC, checking for 4 hours difference or not.

Most of Brazil is 3 hours behind UTC in the standard time, and 2 hours behind UTC in the daylight time. So this code probably won't work for you. You can read more in this Wikipedia article.

Daylight Saving Time is very different all over the world, so if you intend to use this approach then you will have to modify your code to match the time zone of the server that it's running on.

Personally, I would recommend not doing this in SQL at all. Time zone conversions aren't really the realm of the database. They work much better in application code. You should work with UTC in your database, and convert it to Brazil or whatever time zone you require in your application.

Since you said this was an ASP.Net MVC4 application, I recommend you either use the .net TimeZoneInfo class, or use the excellent Noda Time library to do your conversions in your .Net code.

Using TimeZoneInfo:

DateTime utcDT = // ... your UTC value returned from the database
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById(
                             "E. South America Standard Time");     // Brazil
DateTime brazilDT = TimeZoneInfo.ConvertTimeFromUtc(utcDT, tz);

Using Noda Time:

DateTime utcDT = // ... your UTC value returned from the database
Instant instant = Instant.FromDateTimeUtc(utcDT);
DateTimeZone tz = DateTimeZoneProviders.Tzdb["America/Sao_Paulo"];  // Brazil
ZonedDateTime brazilZDT = instant.InZone(tz);
DateTime brazilDT = brazilZDT.ToDateTimeUnspecified();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top