"how do i convert utc to pst or pdt depending upon what the current time is in california?" Code Answer

3

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
By Jan Aagaard Meier on April 6 2022

Answers related to “how do i convert utc to pst or pdt depending upon what the current time is in california?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.