4

If we provide the name of timezone region like "America/Phoenix", is there any way to get the current date and time in C#?

I have tried the following code:-

TimeZoneInfo ZoneName = System.TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time");
DateTime dataTimeByZoneId = System.TimeZoneInfo.ConvertTime(DateTime.Now,System.TimeZoneInfo.Local, ZoneName);

but it takes/expects the input as "US Standard Time Zone". I want the input to be as "America/Phoenix". Please do let me know if we have any options/method in C# to achieve this?

Rohit416
  • 3,416
  • 3
  • 24
  • 41
Neharika
  • 95
  • 11
  • 1
    for handling time and date related tasks I would suggest to use Noda Time. See http://nodatime.org/ for more information. – Ikaso Feb 22 '14 at 06:18
  • check out this [**link**](http://stackoverflow.com/questions/17974633/get-timezone-offset-of-server-in-c-sharp). it might help you :) – Rohit416 Feb 22 '14 at 06:20

1 Answers1

1

Time zone id's like America/Phoenix come from the IANA time zone database. .Net's TimeZoneInfo class does not use that data. See the timezone tag wiki for details.

To use IANA time zone identifiers in .NET, you should look at Noda Time. Here is how you get the current local time for America/Phoenix using Noda Time:

Instant now = SystemClock.Instance.Now;
DateTimeZone tz = DateTimeZoneProviders.Tzdb["America/Phoenix"];
ZonedDateTime zdt = now.InZone(tz);

// Then depending on what your needs are, pick one of the following:
LocalDateTime ldt = zdt.LocalDateTime;
DateTime dt = zdt.ToDateTimeUnspecified();
DateTimeOffset dto = zdt.ToDateTimeOffset();
Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575