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
基础教程推荐
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
