gpt4 book ai didi

c# - 将字符串转换为日期

转载 作者:太空宇宙 更新时间:2023-11-03 20:12:09 25 4
gpt4 key购买 nike

我想将 dd/MM/yyyy 转换为 MM/dd/yyyy

我的代码:

string g = "20-1-1999";
DateTime dt = DateTime.ParseExact(g, "dd/MM/yyyy", CultureInfo.InvariantCulture);

错误信息:

String was not recognized as a valid DateTime.

最佳答案

您必须在格式字符串中为月份提供单个 M。您可以阅读有关格式说明符 MM 的更多信息,here和 M here .您还需要使用 - 作为分隔符而不是 /

DateTime.ParseExact(g, "dd-M-yyyy", CultureInfo.InvariantCulture);

如果您希望天数是个位数,您也可以为天数输入单个 d

DateTime.ParseExact(g, "d-M-yyyy", CultureInfo.InvariantCulture);

“MM”自定义格式说明符

The "MM" custom format specifier represents the month as a number from 01 through 12 (or from 1 through 13 for calendars that have 13 months). A single-digit month is formatted with a leading zero, MSDN

“M”自定义格式说明符

The "M" custom format specifier represents the month as a number from 1 through 12 (or from 1 through 13 for calendars that have 13 months). A single-digit month is formatted without a leading zero, MSDN.

关于c# - 将字符串转换为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19342456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com