PST to UTC Date
I had a requirement to return customer usage between two days, but database saved all usage records with end of the day PST time in UTC dates. Since API accepts date only, database has records with UTC, API need to convert date into end of the day and convert same into UTC to retrive right DB records.
Eg -
Given date - 4/30/2022
Database has record saved as- 5/1/2022 6:59:59 AM +00:00 (4/30/2022 23:59:59 PST)
Since DB saved usage dated 4/30 as 5/1 in UTC, API would miss last record if no date conversion implemented. The below code converts given date only string into end of the day for the intended timezone with UTC format to compare records and include last record with given date ranges.
//Get Pacific Time from the machine.
var pacificTimeZone = "America/Los_Angeles"; //for linux env
if (Environment.OSVersion.VersionString.Contains("Windows"))
pacificTimeZone = "Pacific Standard Time";
var pstZone = TimeZoneInfo.FindSystemTimeZoneById(pacificTimeZone);
var utcNow = DateTime.UtcNow;
var pacificNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, pstZone);
//Get the offset to account for Daylight Savings
var offSet = pacificNow - utcNow;
Console.WriteLine(offSet);
var endTime = DateTimeOffset.Parse("2022-04-30");
//set end of the day for the given date with time offset
DateTimeOffset originalTime = new DateTimeOffset(endTime.Year, endTime.Month, endTime.Day, 23, 59, 59, offSet);
DateTimeOffset utcTime = originalTime.UtcDateTime;
Console.WriteLine("{0}, {1}", originalTime, utcTime);
Comments