C#字符串日期时间与时区 [英] C# string to DateTime with timezone

查看:118
本文介绍了C#字符串日期时间与时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想格式化字符串: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

You should try using DateTimeOffset instead of the DateTime

DateTimeOffset result = DateTimeOffset.Parse("2012-04-20 10:10:00+0200",CultureInfo.InvariantCulture);

下面你得到的偏移量(2小时)也可能与你的日期时间来计算(10:10 )值并获得所需的OUT输出(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);



在这里,你获得偏移(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)

这篇关于C#字符串日期时间与时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆