Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert UTC to PST or PDT depending upon what the current time is in California?

Tags:

timezone

c#

.net

I cannot use DateTime.Now because the server is not necessarily located in Calfornia

like image 532
Abhishek Iyer Avatar asked Feb 21 '13 22:02

Abhishek Iyer


People also ask

How do you convert UTC to specific time zones?

The following example converts Coordinated Universal Time (UTC) to Central Time. let timeUtc = DateTime. UtcNow try let cstZone = TimeZoneInfo. FindSystemTimeZoneById "Central Standard Time" let cstTime = TimeZoneInfo.

Is UTC 7 hours ahead of PST?

UTC is 8 hours ahead of Pacific Standard Time (e.g., 0000 UTC is 1600 PST the previous day, while 1200 UTC is 0400 PST the same day), and 7 hours ahead of Pacific Daylight Time (e.g., 0000 UTC is 1700 PDT the previous day, while 1200 UTC is 0500 PDT the same day).

Are we in PST or PDT right now?

Currently observing PDT. Areas with same time currently (UTC -7).


1 Answers

Two options:

1) Use TimeZoneInfo and DateTime:

using System;

class Test
{
    static void Main()
    {
        // Don't be fooled - this really is the Pacific time zone,
        // not just standard time...
        var zone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
        var utcNow = DateTime.UtcNow;
        var pacificNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, zone);

        Console.WriteLine(pacificNow);
    }
}

2) Use my Noda Time project :)

using System;
using NodaTime;

class Test
{
    static void Main()
    {
        // TZDB ID for Pacific time
        DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
        // SystemClock implements IClock; you'd normally inject it
        // for testability
        Instant now = SystemClock.Instance.Now;

        ZonedDateTime pacificNow = now.InZone(zone);        
        Console.WriteLine(pacificNow);
    }
}

Obviously I'm biased, but I prefer to use Noda Time, primarily for three reasons:

  • You can use the TZDB time zone information, which is more portable outside Windows. (You can use BCL-based zones too.)
  • There are different types for various different kinds of information, which avoids the oddities of DateTime trying to represent three different kinds of value, and having no concept of just representing "a date" or "a time of day"
  • It's designed with testability in mind
like image 73
Jon Skeet Avatar answered Oct 21 '22 23:10

Jon Skeet