在 C# 中将字符串解析为 DateTime [英] Parse string to DateTime in C#

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

问题描述

我有一个日期和时间,格式如下:

"2011-03-21 13:26" //year-month-day hour:minute

如何将其解析为 System.DateTime?

如果可能,我想使用 DateTime.Parse()DateTime.ParseExact() 之类的函数,以便能够手动指定日期格式.

I want to use functions like DateTime.Parse() or DateTime.ParseExact() if possible, to be able to specify the format of the date manually.

推荐答案

DateTime.Parse() 会尝试找出给定日期的格式,通常效果很好.如果您可以保证日期始终采用给定格式,那么您可以使用 ParseExact():

DateTime.Parse() will try figure out the format of the given date, and it usually does a good job. If you can guarantee dates will always be in a given format then you can use ParseExact():

string s = "2011-03-21 13:26";

DateTime dt = 
    DateTime.ParseExact(s, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

(但请注意,如果日期不是预期的格式,使用其中一种 TryParse 方法通常更安全)

(But note that it is usually safer to use one of the TryParse methods in case a date is not in the expected format)

确保检查自定义日期和时间格式字符串 构造格式字符串时,尤其要注意字母的个数和大小写(即MM"和mm"的含义非常不同).

Make sure to check Custom Date and Time Format Strings when constructing format string, especially pay attention to number of letters and case (i.e. "MM" and "mm" mean very different things).

C# 格式字符串的另一个有用资源是 C# 中的字符串格式

Another useful resource for C# format strings is String Formatting in C#

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

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