DateTime.ParseExact字符串格式异常 [英] DateTime.ParseExact string format exception

查看:591
本文介绍了DateTime.ParseExact字符串格式异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个字符串转换成日期时间与下面的C#代码,

I am trying to convert a string into datetime with the following C# code,

DateTime dTo = DateTime.ParseExact(dateTo, "mm/dd/yyyy", CultureInfo.InvariantCulture);



eachtime我通过dateTo为1/1/2010失败,而是需要字符串为01 / 01/2010。

eachtime I pass dateTo as 1/1/2010 it fails, instead it needs the string to be 01/01/2010.

我应该使用什么字符串格式,同时支持01/01/2010和1/1/2010?

What string format should I use to support both 01/01/2010 and 1/1/2010?

推荐答案

使用以下日期格式表达式将允许您使用单或双位数的日和月的元素。

Using the following date format expression will allow you to use either single or double digit day and month elements.

"M/d/yyyy"

请注意,资本<$ C $ ç> M 是显著 - 小写 M 是分钟占位符

Note that the capital M is significant - a lower case m is the placeholder for minutes.

你会发现相关的日期格式字符串这里

You will find more information related to date format strings here.

您可以使用下面的PowerShell命令来测试它们。

You can use the following Powershell command to test them.

[DateTime]::ParseExact('01/01/2010', 'M/d/yyyy', $null)

这篇关于DateTime.ParseExact字符串格式异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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