C# 字符串到带时区的日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10293362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# string to DateTime with timezone
提问by user1264255
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"?
我想用这种格式将字符串:“2012-04-20 10:10:00+0200”格式化为日期时间。所以我认为它必须是“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" :
“V4Vendetta”给出的解决方案:
You should try using DateTimeOffset instead of the DateTime
您应该尝试使用 DateTimeOffset 而不是 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)
在这里你也得到偏移量(2 小时),它可以用你的 DateTime (10:10) 值计算并得到你想要的输出 (result.DateTime + result.Offset)
采纳答案by V4Vendetta
You should try using DateTimeOffsetinstead of the DateTime
你应该尝试使用DateTimeOffset而不是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)
在这里你也得到了Offset(2 hrs) 可以用你的DateTime(10:10) 值计算并得到你想要的输出 (result.DateTime + result.Offset)
回答by Bhargav Bhat
回答by Red Bit
use "2012-04-20 10:10:00 +02:00" instead of " "2012-04-20 10:10:00+0200"
使用“2012-04-20 10:10:00 +02:00”代替“”“2012-04-20 10:10:00+0200”
回答by HW90
Try this:
尝试这个:
DateTime datetime = DateTime.ParseExact("10/10/2009 12:00:00", "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.CurrentCulture);

