0

I am working with .NET, and I am running into issues with time zones. I have separate date and time components, both as strings. I want to parse the string as Eastern Prevailing Time (EPT). However, my system is using the UTC clock, so I cannot assume it to be the local time while parsing.

What's the way to go about this? Is there a library that can come in handy?

Currently, I am doing the following:

const string DateFormat = "yyyyMMdd";
const string TimeFormat = "HH:mm:ss";

if (DateTime.TryParseExact(date_string, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateOnly))
{
    if (DateTime.TryParseExact(time_string, TimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var timeOnly))
    {
        return dateOnly.Date + timeOnly.TimeOfDay;
    }
    return dateOnly.Date;
}

The current implementation parses the DateTime values as UTC, but we know that these are in EPT. If I were to convert the parsed DateTime to EPT, then the actual time would change along with the time zone. Changing the offset manually doesn't help either, since it does not take into account daylights savings.

Yash Jain
  • 23
  • 3
  • What does your input date string look like. If it has a timezone in the string it will correctly get parse correctly. If input doesn't have a timezone than you need to modify the culture (IformatProvider) to be EPT. See : https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parse?view=net-7.0 – jdweng Aug 02 '23 at 13:01
  • 1
    Use DateTimeOffset with TimeZoneInfo to generate your date/time object. You may have to specify the kind depending on the string. – GH DevOps Aug 02 '23 at 13:03
  • Is this helpful? https://stackoverflow.com/questions/24783489/convert-from-one-timezone-to-another-taking-into-consideration-daylight-saving – Lajos Arpad Aug 02 '23 at 13:38
  • Or this? https://stackoverflow.com/questions/75986962/convert-date-and-time-to-another-based-on-timezone – Heiko Theißen Aug 04 '23 at 11:37

0 Answers0