Search code examples
c#datetimeutcformatexception

How to convert Datetimes into UTC based timing values to compare timings- C#


I've string (variable is fileDate) with Date values in the following format:

2/12/2011 11:58 AM

Now I want to convert this to a date and then to UTC time based as I've problems in comparing dates in different machines, so *I always want to convert all strings (which are getting compared) to Utc_date values.*

I tried this code below but it did not work as I'm not able to convert the above string to Datetime based (as it does not have seconds).

DateTime date = Convert.ToDateTime(fileDate);
date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
fileDate = date.ToString("MM/dd/yyyy hh:mm tt");

Above did not work showing FormatException. Can you pl help?


Solution

  • To start with, I'd suggest using DateTime.ParseExact or TryParseExact - it's not clear to me whether your sample is meant to be December 2nd or February 12th. Specifying the format may well remove your FormatException.

    The next problem is working out which time zone you want to convert it with - are you saying that 11:58 is a local time in some time zone, or it's already a UTC time?

    • If it's a local time in the time zone of the code which is running this, you can use DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal to do it as part of parsing.
    • If it's already a universal time, use DateTimeStyles.AssumeUniversal
    • If it's a local time in a different time zone, you'll need to use TimeZoneInfo to perform the conversion.

    Also, if it's a local time you'll need to consider two corner cases (assuming you're using a time zone which observes daylight saving time):

    • A local time may be skipped due to DST transitions, when the clocks go forward. So if the clocks skip from 1am to 2am, then 1:30am doesn't exist at all.
    • A local time may be ambiguous due to DST transitions, when the clocks go back. So if the clocks go back from 2am to 1am, then 1:30am occurs twice at different UTC times - which occurrence are you interested in?

    You should decide how you want to handle these cases, and make sure they're covered in your unit tests.

    Another option is to use my date and time library, Noda Time, which separates the concepts of "local date/time" and "date/time in a particular time zone" (and others) more explicitly.