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

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

问题描述

我有一个DateTime值作为字符串,每次日期格式可能不同。

如何将此字符串转换为DateTime?

I have a DateTime value as string, the date format may be different each time.
How to convert this string to DateTime?

推荐答案

您可以看到DateTime.TryParse是否为您转换它,或者您可以逐个尝试使用可能格式列表的DateTime.TryParseExact,直到一个工作。我建议不要使用DateTime.Parse或DateTime.ParseExact,因为如果转换失败,它们会引发异常。



一般来说,你应该避免允许用户输入日期任何格式。要么使用单独的day \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 2015年1月2日或2月1日?除非设置区域设置和格式,否则永远无法判断。
You can see if DateTime.TryParse converts it for you, or you can try DateTime.TryParseExact with a list of possible formats one by one until one works. I'd advise against using DateTime.Parse or DateTime.ParseExact as they will raise exceptions if the conversion fails.

In general you should avoid allowing users to enter dates in any format. Either use separate day\month\year boxes or a date picker etc. In some cases you might just have to accept that the date is wrong if the user doesn't follow your preferred convention, eg is 1\2\2015 Jan 2nd or Feb 1st? You can never tell unless you set the locale and format.


您应该使用DateTime的Parse方法 - https://msdn.microsoft.com/en-us/library/system.datetime.parse%28v=vs.110%29.aspx [ ^ ]
You should use Parse method of DateTime - https://msdn.microsoft.com/en-us/library/system.datetime.parse%28v=vs.110%29.aspx[^]


使用DateTime.Parse()函数将String转换为DateTime格式。



例如

Use DateTime.Parse() function to convert String into DateTime format.

E.g.
<br />
string strTime ="Wed, 06 May 2015 07:11:21 GMT";<br />
DateTime time = DateTime.Parse(strTime);<br />



请参阅链接以获取更多详细信息

http://www.dotnetperls.com/datetime-parse [ ^ ]


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

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