简体   繁体   English

带有时区的C#字符串到DateTime

[英]C# string to DateTime with timezone

I want to format the string : "2012-04-20 10:10:00+0200" to a dateTime with this format. 我想将字符串:“2012-04-20 10:10:00 + 0200”格式化为具有此格式的dateTime。 so I think it must be "yyyy-MM-dd hh:mm:ss zzz"? 所以我认为它必须是“yyyy-MM-dd:mm:ss zzz”?

when I tried this 当我试着这个

   // 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);

SOLUTION GIVEN BY "V4Vendetta" : 由“V4Vendetta”提供的解决方案:

You should try using DateTimeOffset instead of the DateTime 您应该尝试使用DateTimeOffset而不是DateTime

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

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) 在这里你可以获得Offset(2小时),可以使用你的DateTime(10:10)值计算并得到你想要的输出(result.DateTime + result.Offset)

You should try using DateTimeOffset instead of the DateTime 您应该尝试使用DateTimeOffset而不是DateTime

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

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) 在这里你可以获得Offset (2小时),可以使用你的DateTime (10:10)值计算并得到你想要的输出(result.DateTime + result.Offset)

The MSDN article here seems to have exactly what you're looking for. 这里的MSDN文章似乎正是您正在寻找的内容。 Per said article, you should be using {0:MM/dd/yy H:mm:ss zzz} 根据上述文章,你应该使用{0:MM/dd/yy H:mm:ss zzz}

使用“2012-04-20 10:10:00 +02:00”而不是“”2012-04-20 10:10:00 + 0200“

尝试这个:

DateTime datetime = DateTime.ParseExact("10/10/2009 12:00:00", "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.CurrentCulture);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM