将任何 DateTime 字符串格式转换为美国短日期 "MM-dd-yyyy"
Convert any DateTime string format to US short date "MM-dd-yyyy"
我在这里尝试编写一个通用代码来将任何提供的有效 date
/ datetime
格式转换为 美国短日期格式.
下面是我正在尝试的代码:
public static string ConvertToUSDateFormat(string dateString)
{
string[] formats = {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd","yyyy-MM-dd hh:mm:tt", "dd-MM-yyyy hh:mm:tt", "M/d/yyyy", "dd MMM yyyy","dd/MM/yyyy hh:mm:tt", "MM-dd-yyyy hh:mm:tt", "dd-MM-yyyy h:mm:tt"};
string convertedDate = DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MM/dd/yyyy");
return convertedDate;
}
我提供给这个方法的输入是19-01-2018 10:55:52
.
但是此代码抛出错误:字符串未被识别为有效的日期时间。
"19-01-2018 10:55:52"
与格式数组中不存在的以下格式匹配。
"dd-MM-yyyy hh:mm:ss"
我在这里尝试编写一个通用代码来将任何提供的有效 date
/ datetime
格式转换为 美国短日期格式.
下面是我正在尝试的代码:
public static string ConvertToUSDateFormat(string dateString)
{
string[] formats = {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd","yyyy-MM-dd hh:mm:tt", "dd-MM-yyyy hh:mm:tt", "M/d/yyyy", "dd MMM yyyy","dd/MM/yyyy hh:mm:tt", "MM-dd-yyyy hh:mm:tt", "dd-MM-yyyy h:mm:tt"};
string convertedDate = DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MM/dd/yyyy");
return convertedDate;
}
我提供给这个方法的输入是19-01-2018 10:55:52
.
但是此代码抛出错误:字符串未被识别为有效的日期时间。
"19-01-2018 10:55:52"
与格式数组中不存在的以下格式匹配。
"dd-MM-yyyy hh:mm:ss"