简体   繁体   中英

C# string to DateTime with timezone

I want to format the string : "2012-04-20 10:10:00+0200" to a dateTime with this format. so I think it must be "yyyy-MM-dd hh:mm:ss zzz"?

when I tried this

   // starttime =  {20/04/2012 10:10:00} without my +0200!
DateTime starttime = Convert.ToDateTime("2012-04-20 10:10:00+0200",CultureInfo.CurrentCulture);
// And this gave me a format exception : {System.FormatException: String was not recognized as a valid DateTime.
        DateTime result = DateTime.ParseExact("2012-04-20 10:10:00+0200", "yyyy-MM-dd hh:mm:ss zzz", CultureInfo.InvariantCulture);

SOLUTION GIVEN BY "V4Vendetta" :

You should try using DateTimeOffset instead of the DateTime

DateTimeOffset result = DateTimeOffset.Parse("2012-04-20 10:10:00+0200",CultureInfo.InvariantCulture);

Here you get the Offset (2 hrs) too which could be computed with your DateTime (10:10) value and get your desired out put (result.DateTime + result.Offset)

You should try using DateTimeOffset instead of the DateTime

DateTimeOffset result = DateTimeOffset.Parse("2012-04-20 10:10:00+0200",CultureInfo.InvariantCulture);

Here you get the Offset (2 hrs) too which could be computed with your DateTime (10:10) value and get your desired out put (result.DateTime + result.Offset)

The MSDN article here seems to have exactly what you're looking for. Per said article, you should be using {0:MM/dd/yy H:mm:ss zzz}

使用“2012-04-20 10:10:00 +02:00”而不是“”2012-04-20 10:10:00 + 0200“

尝试这个:

DateTime datetime = DateTime.ParseExact("10/10/2009 12:00:00", "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.CurrentCulture);

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