麻烦从字符串解析DateTime [英] Troubles parsing DateTime from string

查看:57
本文介绍了麻烦从字符串解析DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试解析从每隔几分钟从Web下载的xml中获取的字符串.字符串如下所示:

I am currently trying to parse a string that is obtained from an xml that is downloaded from the web every few minutes. The string looks like this:

Thu Jul 12 08:39:56 GMT+0100 2012

起初,我只是做了一个 string.split ,并取出了所有时间( GMT + 0100 2012 ),然后在日期之后插入了2012.

At first I just did a string.split and took out everything after the time (GMT+0100 2012) and inserted 2012 after the date.

这很好,直到日期更改为:

This worked great until the date changed to:

Thu Jul 12 08:39:56 GMT+0000 2012

所以我想动态地修改GMT +,无论他们用c#向我发送该字符串是什么.

So I would like to dynamically pasre the GMT+ whatever as they send me that string in c#.

任何建议将不胜感激.

推荐答案

您可以将 DateTime.ParseExact

如果字符串和格式字符串不完全匹配,这将引发格式异常,因此您可能要使用 DateTime.TryParseExact ,如果该字符串返回 false 失败.

This will throw a format exception if the string and format string do not match exactly, so you may want to use DateTime.TryParseExact that will return a false if it fails.

您可能希望使用保留时区信息的 DateTimeOffset 代替 DateTime ,例如评论-此可能对您的应用很重要.

Instead of DateTime you may want to use DateTimeOffset that preserved timezone information , as @Keith commented - this may be important to your application.

这篇关于麻烦从字符串解析DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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