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
基础教程推荐
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
