C# string to DateTime with timezone(带有时区的 C# 字符串到 DateTime)
问题描述
我想将字符串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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有时区的 C# 字符串到 DateTime


- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01