[英]How to convert Feb 19, 2015,22:19:50 to 2/19/2015 22:19:50 in C#?
How can I convert Feb 19, 2015,22:19:50
to 2/19/2015 22:19:50
in C#? 如何在C# 2/19/2015 22:19:50
年Feb 19, 2015,22:19:50
转换为Feb 19, 2015,22:19:50
?
I have tried something like below 我已经尝试过以下内容
DateTime dateTime = DateTime.ParseExact("Feb 19, 2015,22:19:50",
"MMM dd, yyyy;HH:mm:ss",
CultureInfo.InvariantCulture);
But I got following error 但我得到以下错误
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: String was not recognized as a valid DateTime." mscorlib.dll中发生了'System.FormatException'类型的第一次机会异常。附加信息:字符串未被识别为有效的DateTime。”
First of all, your string and format doesn't match exactly . 首先,你的字符串和格式不完全匹配。 In your string, you have a comma between your years and hours, but in your format you have a semicolon. 在字符串中,年份和小时之间用逗号分隔,但在格式上则用分号分隔。 When you have a custom parsing with DateTime.ParseExact
or DateTime.TryParseExact
methods, your string and format must match exactly based on IFormatProvider
you use. 当您使用DateTime.ParseExact
或DateTime.TryParseExact
方法进行自定义解析时,您的字符串和格式必须完全基于您使用的IFormatProvider
匹配。
After you parse your string correctly, you can format it with .ToString()
method wih M/dd/yyyy HH:mm:ss
format and a culture that have /
as a DateSeparator
and :
as a TimeSeparator
like InvariantCulture
. 正确解析字符串后,可以使用.ToString()
方法格式化M/dd/yyyy HH:mm:ss
格式,并使用/
作为DateSeparator
和:
作为TimeSeparator
如InvariantCulture
。
string s = "Feb 19, 2015,22:19:50";
DateTime dt;
if(DateTime.TryParseExact(s, "MMM dd, yyyy,HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("M/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
// 2/19/2015 22:19:50
}
Here a demonstration . 这里有示范 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.