Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current Time of Timezone

Tags:

timezone

c#

I have different timezones and their GMT and DST. Example:

TimeZoneId        |   GMT offset  |   DST offset  
                  |  1. Jan 2010  |  1. Jul 2010
--------------------------------------------------
America/Adak      |    -10.0      |     -9.0
America/Anchorage |     -9.0      |     -8.0
America/Anguilla  |     -4.0      |     -4.0
America/Antigua   |     -4.0      |     -4.0
America/Araguaina |     -3.0      |     -3.0

This timezones are provided by Geoname.

How can I calculate the current time for any timezone knowning GMT and DST in C#/.NET?

Update: To specify better, I provide "America/Antigua" and I need the current time in "America/Antigua".

like image 663
Professional Koder Avatar asked Jul 14 '10 13:07

Professional Koder


3 Answers

TimeZoneInfo.ConvertTimeFromUtc(mytime, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
like image 171
Tesserex Avatar answered Nov 03 '22 20:11

Tesserex


The time zone IDs you've given are the ones from the IANA time zone database, aka TZDB (aka Olson, aka tz). They're not supported by .NET (although .NET Core running on Linux/Mac will probably do what you want).

My Noda Time project does support them though. You'd use:

var zoneId = "America/Antigua";
var zone = DateTimeZoneProviders.Tzdb[zoneId];
var now = SystemClock.Instance.GetCurrentInstant();
var zoned = now.InZone(zone);
Console.WriteLine(zoned);

That uses the SystemClock explicitly - in real code I'd advise you to accept an IClock via dependency injection for testability - inject SystemClock.Instance when running the application, but use FakeClock for testing.

Alternative equivalent code demonstrating ZonedClock:

var zoneId = "America/Antigua";
var zone = DateTimeZoneProviders.Tzdb[zoneId];
var systemClock = SystemClock.Instance;
var zonedClock = systemClock.InZone(zone);
var zoned = zonedClock.GetCurrentZonedDateTime();
Console.WriteLine(zoned);
like image 39
Jon Skeet Avatar answered Nov 03 '22 21:11

Jon Skeet


private static ReadOnlyCollection<TimeZoneInfo> _timeZones = TimeZoneInfo.GetSystemTimeZones();

public static DateTime ToUsersTime(this DateTime utcDate, int timeZoneId)
{
    return TimeZoneInfo.ConvertTimeFromUtc(utcDate, timeZones[timeZoneId]);
}

An example of converting a UTC date to a user's date using the TimeZoneInfo class (.NET 3.5+).

like image 45
Simon Hazelton Avatar answered Nov 03 '22 21:11

Simon Hazelton