问题描述
我想将字符串2012-04-20 10:10:00+0200"格式化为具有这种格式的日期时间.所以我认为它必须是yyyy-MM-dd hh:mm:ss zzz"?
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"?
当我尝试这个时
// 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);
V4Vendetta"提供的解决方案:
SOLUTION GIVEN BY "V4Vendetta" :
您应该尝试使用 DateTimeOffset 而不是 DateTime
You should try using DateTimeOffset instead of the DateTime
DateTimeOffset result = DateTimeOffset.Parse("2012-04-20 10:10:00+0200",CultureInfo.InvariantCulture);
在这里您也可以获得偏移量(2 小时),它可以使用您的 DateTime (10:10) 值计算并获得您想要的输出 (result.DateTime + result.Offset)
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)
推荐答案
你应该尝试使用 DateTimeOffset
而不是 DateTime
You should try using DateTimeOffset
instead of the DateTime
DateTimeOffset result = DateTimeOffset.Parse("2012-04-20 10:10:00+0200",CultureInfo.InvariantCulture);
在这里您也可以得到 Offset
(2 小时),这可以用您的 DateTime
(10:10) 值计算并获得您想要的输出(result.DateTime+ 结果.偏移)
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)
这篇关于带有时区的 C# 字符串到 DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!