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?
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?
DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal
to do it as part of parsing.DateTimeStyles.AssumeUniversal
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):
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.