如何字符串转换为日期和时间 [英] How to convert string to date time

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

问题描述

 string value =     "Sat Apr 28 2012 11:00:00 GMT-0400 (Eastern Daylight Time)"

我需要转换为日期和时间

I need to convert to date time

我试着这样做:

 DateTime datetime = DateTime.ParseExact(value, "MM/dd/yyyy hh:mm", null);

 DateTime datetime2 = Convert.ToDateTime(value);

例外:字符串未被识别为有效的DateTime

Exception: String was not recognized as a valid DateTime.

推荐答案

您字符串不匹配您的格式。

Your string doesn't match your format.

您必须设法将其转换之前,解析字符串了一下。例如,2012年4月28日11:00:00能够被解析。但是,你需要休息自己转换它。

You need to parse that string a bit before trying to convert it. For example, "Apr 28 2012 11:00:00" could be parsed. But, you'll need to convert the rest of it yourself.

您可能要考虑使用的DateTimeOffset 这里记录,因为它可以容纳相对时间为UTC,喜欢你的字符串。

You may want to look into using DateTimeOffset documented here, because it can hold time relative to UTC, like your string.

找到它的文档,pretty接近你有什么

Found this is the documentation, pretty close to what you have

// Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
try
{
    result = DateTimeOffset.ParseExact(dateString, format, provider);
    Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
   Console.WriteLine("{0} is not in the correct format.", dateString);
} 

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

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