日期时间从字符串解析 [英] Datetime parse from string

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

问题描述

我正在处理EML文件并收到电子邮件发送数据,如Fri,2013年4月5日15:47:24 -0400(美国东部时间),我不知道日期时间字符串中包含多少格式和GMT,有没有人有通用的想法如何解析它到日期时间?



我尝试过:



DateTime dateTime;



if(DateTime.TryParse(dateString,CultureInfo.InvariantCulture,DateTimeStyles.AssumeUniversal,out dateTime))

{

return dateTime.ToUniversalTime();

}

I am processing the EML file and getting the email send data like Fri, 5 Apr 2013 15:47:24 -0400 (EDT), i don't know how many format and GMT that include on the date time string, does any one have generic idea how to parse it into datetime?

What I have tried:

DateTime dateTime;

if (DateTime.TryParse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dateTime))
{
return dateTime.ToUniversalTime();
}

推荐答案

这有点不寻常日期格式 - 这是问题的最后一点。

这是有效的:

That's a slightly unusual date format - it's the final bit that's the problem.
This works:
string dateString = "Fri, 5 Apr 2013 15:47:24 -0400 (EDT)";
DateTime dt;
if (DateTime.TryParseExact(dateString.Substring(0, dateString.Length - 8), "ddd, d MMM yyyy HH:mm:ss zz", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dt))
    {
    Console.WriteLine(dt);
    }

但是 - 它忽略字符串末尾的时间偏移分钟和TZ代码。如果分钟始终为零,则无关紧要 - 否则您需要将它们重新格式化为-04:00而不是-0400,并将时区代码从zz更改为zzz以使其工作。

But - it ignores the Time offset minutes and TZ code at the end of the string. If the minutes are always zero, then it won't matter - otherwise you need to reformat them as "-04:00" instead of "-0400" and change the timezone code from "zz" to "zzz" for it to work.


我们可以使用以下方法从字符串转换DateTime对象:

We can use following methods to convert DateTime object from string:
Convert.ToDateTime()

DateTime.Parse()

DateTime.ParseExact()

DateTime.TryParse()

DateTime.TryParseExact()





现在出现一个问题,为什么我们有这么多的解析方法。原因是每种方法都用于不同的目的。



如果希望能够尝试解析并立即处理无效数据(而不是抛出异常),请使用TryParse() ),当你期望的格式不是标准格式,或者你想限制一种特定的标准格式以提高效率时,和ParseExact()。



如果你'确保字符串是有效的DateTime,并且您知道格式,您还可以考虑DateTime.ParseExact()或DateTime.TryParseExact()方法。请关注此处



如果您想了解DateTime格式,请点击以下链接:

在C#中使用DateTime对象 [ ^ ]


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

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