日期时间转换时出现错误

3

我有一个字符串的格式为:19/8/1988

注意: String DateOfBirth=" 19/8/1988"

当我使用Datetime.parse(DateOfBirth)时,它会给出无效日期格式错误

我也无法使用cdate(DateOfBirth)

当我以mm/dd/yyyy的格式输入字符串,即8/19/1988时,就不会出现错误。

请帮我将字符串转换为mm/dd/yyyy格式的日期。


尝试使用TryParseExact而不是Parse,请参考http://msdn.microsoft.com/en-us/library/h9b85w22.aspx - Kamil Budziewski
DateTime.ParseExact 只需在 StackOverflow 上搜索,您就会找到数百万个答案。 - I4V
这也给了我同样的错误,所以我才发了问题。 - C Sharper
1
请注意,mm 表示分钟而不是月份,因此在使用 TryParseExact 时,请写成 MM - Kamil Budziewski
@NavatKayAahe,你还没有发布那个吗? - Kamil Budziewski
4个回答

6

小写的mm表示分钟而不是月份,您需要使用大写的M(单个字符)。

但是还需要使用CultureInfo.InvariantCultureParseExact。否则,您的当前区域设置将用于获取日期分隔符,这不一定是/(在许多国家中是.)。

因此,这适用于任何文化:

DateTime.ParseExact("19/8/1988", "dd/M/yyyy", CultureInfo.InvariantCulture)

演示版

"/"自定义格式说明符

如果您想验证给定的日期字符串,可以使用DateTime.TryParseExact:

DateTime dt; 
if(DateTime.TryParseExact("19/8/1988", "dd/M/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) 
{
    // success, dt contains the correct date now
} 
else 
{
    // not a valid date 
}

2
请注意,在日期时间之前有空格,您需要在使用给定格式进行解析之前删除该字符串。
var date = DateTime.ParseExact(DateOfBirth.Trim(), "d/M/yyyy", CultureInfo.InvariantCulture);

如果你有多种日期时间格式,那么

var date = DateTime.ParseExact(DateOfBirth.Trim(), new string[] {"d/M/yyyy","M/d/yyyy"} , CultureInfo.InvariantCulture, DateTimeStyles.None);

1
我知道你遇到错误的原因,系统默认将日期时间格式设置为美国日期格式(mm/dd/yyyy),请在你的系统中更改此格式,前往控制面板-->区域和语言-->格式-->其他设置-->日期以更改所需的格式。这样手动解决了你的问题,或者可以通过编程来解决。
DateTime.ParseExact("19/8/1988", "dd/M/yyyy", CultureInfo.InvariantCulture)

1

网站开发者,这是一段vb代码,需要转换为C#。

Dim time As DateTime = DateTime.Now
Dim format As String = "dd/MM/yyyy" 
' you can set format to both "dd/MM/yyyy" or "d/MM/yyyy"

MsgBox(time.ToString(format))

让我知道它是否有帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接