将dd / mm / yyyy格式的string转换为Datetime
我是DotNet和C#的新手。 我想将mm/dd/yyyy格式的string转换为DateTime对象。 我尝试了像下面的parsing函数,但它是抛出一个运行时错误。
DateTime dt=DateTime.Parse("24/01/2013");
关于如何将其转换为date时间的任何想法?
您需要使用格式为"dd/MM/yyyy" DateTime.ParseExact
DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
如果您使用d/M/yyyy作为格式,则会更安全,因为这样可以处理单个数字和两位数的日/月。 但这真的取决于你是否期待单/双数字值。
date格式day/Month/Year可能是某些文化的可接受的date格式。 例如对于加拿大文化en-CA DateTime.Parse将工作如下:
DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));
要么
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA"); DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture
上述两行都可以工作,因为string的格式对于en-CA文化来说是可以接受的。 由于您不提供任何文化到您的DateTime.Parse调用,您当前的文化是用于parsing不支持date格式。 在DateTime.Parse阅读更多关于它的信息。
另一种parsing方法是使用DateTime.TryParseExact
DateTime dt; if (DateTime.TryParseExact("24/01/2013", "d/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) { //valid date } else { //invalid date }
.Net框架中的TryParse组方法不会在无效值上抛出exception,而是返回一个表示成功或失败parsing的bool值。
请注意 ,我已经分别使用了单日d和月M 单一的d和M工作日/月和单/双数字。 所以对于格式d/M/yyyy有效值可以是:
- “24/01/2013”
- “24/1/2013”
- “2013年4月12日”// 2013年12月4日
- “2013年4月12日”
为进一步阅读你应该看到: 自定义date和时间格式string
使用DateTime.ParseExact
string strDate = "24/01/2013"; DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)
- DateTime.ParseExact
null将使用当前的文化,这是有点危险的。 尝试提供特定的文化
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)
您可以使用"dd/MM/yyyy"格式在DateTime.ParseExact使用它。
使用指定的格式和文化特定的格式信息,将date和时间的指定string表示forms转换为与DateTime等效的forms。 string表示的格式必须完全匹配指定的格式。
DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
这是一个DEMO 。
有关更多信息,请查看Custom Date and Time Format Strings