Format String to Datetime with Timezone

61,369

Central Daylight Time

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

Share:
61,369
Warz
Author by

Warz

JavaScript and Swift and Python. Okay maybe just Python

Updated on August 14, 2020

Comments

  • Warz
    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
    Greg over 11 years
    what happens if CDT has daylight savings time and becomes -4?
  • Warz
    Warz over 11 years
    where 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
    rumburak over 11 years
  • Warz
    Warz over 11 years
    to convert this date to UTC, cant i just dt.ToUniversalTime() ?
  • Greg
    Greg over 11 years
    I 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
    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
    Greg over 11 years
    I 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
    rumburak over 11 years
    @Warz: CDT time is -5, please consider reading CDT wiki document
  • Josh
    Josh almost 4 years
    Please note that IsDaylightSavingTime returns true if the time is daylight time in the TimeZoneInfo.Local timezone, not the one that the DateTime 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 returns false