How do I convert UTC to PST or PDT depending upon what the current time is in California?
.net, c#, timezone
Solution
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
Problem
I cannot use `DateTime.Now` because the server is not necessarily located in Calfornia