Format String to Datetime with Timezone
61,369
Try this:
string dts = "May 16, 2010 7:20:12 AM CDT";
DateTime dt =
DateTime.ParseExact(dts.Replace("CDT", "-05:00"), "MMM dd, yyyy H:mm:ss tt zzz", null);
EDIT:
For daylight savings time please consider DateTime.IsDaylightSavingTime and TimeZone.CurrentTimeZone
Custom Date and Time Format Strings
Comments
-
Warz over 3 years
I have a
string s = "May 16, 2010 7:20:12 AM CDT
that i want to convert into a DateTime object. In the code below i get a Date format cannot be converted error when attempting to parse the text with a known format.timeStamp = matches[0].Groups[1].Value; dt = DateTime.ParseExact(timeStamp, "MMM dd, yyyy H:mm:ss tt", null);
The timezone comes in as CDT UTC... and i think is whats causing the problem or my format?
-
Greg over 11 yearswhat happens if CDT has daylight savings time and becomes -4?
-
Warz over 11 yearswhere do i find the information about off sets and Timezone, i may also get CST as a timezone and need to replace and handle daylight savings time.
-
rumburak over 11 years
-
Warz over 11 yearsto convert this date to UTC, cant i just dt.ToUniversalTime() ?
-
Greg over 11 yearsI think you can. Once you convert the string into a DateTime then you should be able to do .ToUniversalTime(). You need to have it in the right format first though (including daylight savings)
-
Warz over 11 years@Greg could you explain your first comment, "daylight savings time becoming -4", i thought CDT was UTC-5.00 and CST was UTC-6.00 ?
-
Greg over 11 yearsI quite possibly went the wrong way. I live in Sydney and we're UTC +10 normally but in summer UTC+11. I'm not claiming to know the specific timezones, just raising the fact that you can't just use UTC-5, you need to change for daylight savings.
-
rumburak over 11 years@Warz: CDT time is -5, please consider reading CDT wiki document
-
Josh almost 4 yearsPlease note that
IsDaylightSavingTime
returns true if the time is daylight time in theTimeZoneInfo.Local
timezone, not the one that theDateTime
instance you call the method on is set to. How awful is that? If the machine running the app is in UTC, the method always returnsfalse