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


基础教程推荐
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01