I cannot use DateTime.Now
because the server is not necessarily located in Calfornia
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.
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).
Currently observing PDT. Areas with same time currently (UTC -7).
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:
DateTime
trying to represent three different kinds of value, and having no concept of just representing "a date" or "a time of day"If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With