解析使用时区偏移的日期时间

解析使用时区偏移的日期时间

本文介绍了解析使用时区偏移的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些datetimes在我看来是一个奇怪的标准..

I have these datetimes which appear to me to be in an odd standard..

2004/05/17 21:27:16.162 GMT-7

2006/08/01 01:00:00 GMT-7

2010/11/05 13:00:38.844美国/太平洋

2004/05/17 21:27:16.162 GMT-7
2006/08/01 01:00:00 GMT-7
2010/11/05 13:00:38.844 US/Pacific

任何有关C#中如何解析的想法?或者有谁见过他们吗?

Any ideas on how I can parse them in C#? Or has anyone seen them before?

推荐答案

2010/11/05 13:00:38.844 US /太平洋是您无法在纯粹的.Net中解析的东西,至少不是本地化的形式。对于其他人来说,这取决于你是否知道格式。如果你这样做,你可以使用DateTime的 ParseExact()方法:

2010/11/05 13:00:38.844 US/Pacific is something which you cannot parse in pure .Net, at least not in localized form. For others, it really depends on whether you know format. If you do, you can use DateTime's ParseExact() method:

var dateString = "2004/05/17 21:27:16.162 GMT-7";
var anotherDateString = "2006/08/01 01:00:00 GMT-7";
DateTime firstResult;
var success = DateTime.TryParseExact(dateString, "yyyy/MM/dd HH:mm:ss.fff 'GMT'z", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out firstResult);
if (success)
    MessageBox.Show(firstResult.ToString());

DateTime anotherResult;
success = DateTime.TryParseExact(anotherDateString, "yyyy/MM/dd HH:mm:ss 'GMT'z", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out anotherResult);
if (success)
    MessageBox.Show(anotherResult.ToString());

请记住,我使用了InvariantCulture,因为我知道它与 en-US 。为了正确的结果,您需要使用有效的CultureInfo。

Please keep in mind, that I used InvariantCulture because I knew it is exactly the same as en-US. For correct results you would need to use valid CultureInfo.

最后但并非最不重要的是:为什么要解析这些无效格式?我建议修复问题的根源,并使用本地默认格式(取决于当前用户位置的文化和当地时间),而不是创建自己的格式。特殊格式使得理解时间变得更加困难,因为对于最终用户而言,它们不自然。

Last, but not least: why you want to parse these invalid formats anyway? I would suggest to fix the source of the problem and use local default formats (depending on the culture as well as local time for current user's location) rather than creating your own. Special formats make understanding time harder as they are unnatural for end users.

这篇关于解析使用时区偏移的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:37