简体   繁体   中英

How to Parse a Date Time with TimeZone Info

I have following string ,

Thu Sep 24 2015 00:00:00 GMT+0530 (IST)

I tried with following but it's faling.

   var twDate = DateTime.Parse("Thu Sep 24 2015 00:00:00 GMT+0530 (IST) ");

Can not use replace , as IST wont be fixed. Any Ideas?

You need to trim the time zone abbreviation off using normal string operations, then specify a custom date and time format string. For example:

// After trimming
string text = "Thu Sep 24 2015 00:00:00 GMT+0530";
var dto = DateTimeOffset.ParseExact(
    text,
    "ddd MMM d yyyy HH:mm:ss 'GMT'zzz",
    CultureInfo.InvariantCulture);
Console.WriteLine(dto);

Note the use of CultureInfo.InvariantCulture here - you almost certainly don't want to parse using the current thread's current culture.

If your string always has the same format and length, you could use this to get UTC:

String dtstr = "Thu Sep 24 2015 00:00:00 GMT+0530 (IST)";
int zoneMin = int.Parse(dtstr.Substring(29, 2)) * 60 + int.Parse(dtstr.Substring(31, 2));
if (dtstr.Substring(28, 1) == "+") zoneMin = -zoneMin;
DateTime dt = DateTime.Parse(dtstr.Substring(0, 24)).AddMinutes(zoneMin);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM