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

17,204

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
Share:
17,204
Abhishek Iyer
Author by

Abhishek Iyer

Software Engineer, Android Developer, Excited by algorithms, Former ACM ICPC World Finalist. Love to learn and explore. Believe in 'practice makes perfect'.

Updated on June 16, 2022

Comments

  • Abhishek Iyer
    Abhishek Iyer almost 2 years

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

  • HaBo
    HaBo about 8 years
    How can I force it to PST even if it is PDT currently
  • Jon Skeet
    Jon Skeet about 8 years
    @HaBo: I suggest you ask a new question with details of what you're trying to achieve and why. You may be able to find a time zone which is PST all year round, for example.
  • HaBo
    HaBo about 8 years