如何将数据转换为DateTime对象
如何将一般形式“ccyymmdd”的日期字符串转换为 C# 中的 DateTime 对象?
例如,如何将“20100715”转换为 DateTime 对象。
请 - 没有指向 Microsoft 技术文档的 RTFM 链接。
非常感谢...
How do I convert a date string, in the general form of "ccyymmdd" in to a DateTime object in C#?
For example, how would I convert "20100715" in to a DateTime object.
Please - No RTFM links to Microsoft Tech Docs.
Many Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
var dt = DateTime.Parse("your date string").ToString("yymmdd");
我不认为
cc
是有效的日期格式选项?正如理查德指出的,您还可以使用
DateTime.ParseExact
,它允许您使用区域性信息进行解析,或者您可以使用DateTime.TryParseExact
,它与 < code>DateTime.ParseExact,但如果出现异常,则返回空日期,而不是引发异常。编辑:
问题已更新,以便专门返回
DateTime
。在这种情况下,您可以省略我答案的.ToString()
部分。调用DateTime.Parse()
将返回一个DateTime
对象。通过ToString()
获取日期值时,只需传递所需的格式化字符串即可获取所需格式的日期。干杯。
贾斯。
var dt = DateTime.Parse("your date string").ToString("yymmdd");
I don't think
cc
is a valid date formatting option?As Richard points out, you can also use
DateTime.ParseExact
which allows you to use culture information for the parsing, or you can useDateTime.TryParseExact
which is the same asDateTime.ParseExact
, but if there is an exception then a null date is returned rather then an exception being raised.EDIT:
The question has been updated so that a
DateTime
is specifically returned. In that case you can omit the.ToString()
part of my answer. CallingDateTime.Parse()
will return aDateTime
object. When getting the date value viaToString()
, simply pass the required formatting string to get the date in the desired format.Cheers.
Jas.
看看这个和这个
值得一提
Take a look at this and this
And worth a mention
如果您的日期字符串已被清理(借用迈克的答案):
否则:
If your date string is already sanitized (Borrowed from Mike's answer):
Otherwise:
System.DateTime.Parse(yourDateString)
您可能必须先将字符串处理为该方法可以处理的格式。
请参阅 http://msdn.microsoft.com/en-us/library/1k1skd40 .aspx
了解更多信息
System.DateTime.Parse(yourDateString)
You might have to manipulate your string to a format that the method can handle first.
See http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
for more info
我不确定“cc”部分是什么,但有几个选项。
DateTime.Parse(string) 可能能够转换字符串,但如果字符串是非标准格式,您可能需要先进行一些预转换。
I'm not sure what the "cc" part is, but there are a few options.
DateTime.Parse(string) may be able to convert the string, but if the string is in a non-standard format you may have to do some pre-conversion first.