在C#中将字符串转换为日期时间 [英] Convert string to date time in C#
问题描述
我需要转换日期时间格式:' 2016年8月9日星期二00:00:03
'到' 2016-08-09 00:00:03
'。我尝试了下面的解决方案,但没有成功。请帮我转换为' yyyy-MM-dd HH:mm:ss
'格式。在此先感谢。
我尝试过:
private string ParseDateTime( string dateTime)
{
try
{
DateTime dateValue; string UTC_DateTime = ;
if (DateTime.TryParse(dateTime, out dateValue))
{
UTC_DateTime = dateValue.ToLocalTime()。ToString( yyyy-MM-dd HH:mm:ss< /跨度>);
}
其他
{
var date = DateTime.ParseExact(dateTime, ddd MMM dd HH:mm:ss yyyy,CultureInfo.GetCultureInfo( en-us));
UTC_DateTime = date.ToString( yyyy-MM-dd HH:mm:ss );
}
return UTC_DateTime;
}
catch (例外情况)
{
return ;
}
}
首先:a'8月9日星期二00 :00:03 2016
'date 无法转换为'2016-10-09 00:00:03
',因为8月是8个月。
其次,你需要做的就是:
string inputDate = 8月9日星期二00:00:03;
string inputFormat = ddd MMM d hh :mm:ss yyyy;
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo( EN-US跨度>);
DateTime resultDate = DateTime.ParseExact(inputDate,inputFormat,provider);
// resultDate ='2016-08-09 00:00:03'
但是(!),我建议使用DateTime.TryParse [ ^ ]或DateTime.TryParseExact [ ^ ]方法。
< pre lang =C#> DateTime resultDate1;
if (DateTime.TryParseExact(inputDate,inputFormat,provider,System.Globalization.DateTimeStyles.None, out resultDate1))
{
Console.WriteLine( 结果date是'{0}',resultDate1);
}
else
{
Console.WriteLine( 字符串到日期转换失败!);
}
使用DateTime.TryParseExact
,你可以遍历这些格式,即:
string inputDate = 8月10日星期二00:00:03 2016\" 跨度>; // '2016-10-09 00:00:03'。
string [] inputFormats = new string [] {< span class =code-string> MMM d hh:mm:ss yyyy, MMM dd hh:mm:ss yyyy};
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo( EN-US跨度>);
DateTime resultDate = new DateTime( 1900 , 1 , 1 );
foreach ( string format in inputFormats)
{
if (DateTime.TryParseExact(inputDate。 Substring( 4 ,inputDate.Length-4),格式,提供者,System.Globalization.DateTimeStyles.None, out resultDate))
{
Console.WriteLine( 结果日期为'{0}',resultDate);
break ;
}
}
if (resultDate == new DateTime( 1 , 1 , 1 ))
{
Console.WriteLine( 字符串到日期转换失败。格式不明!);
}
添加这些行,
private static string ParseDateTime( string dateTime)
{
var parts = dateTime.Split(' ');
var day = parts [ 2 ];
var validDay = day.Length == 1 ? 0 + day:day;
dateTime = dateTime.Replace( + day + , + validDay + );
尝试
{
您传递的天是d
格式,但您在解析 >dd
格式,因此必须通过添加0 0来格式化为
dd
的单位数字code> at前缀
一种非常简单的方法可满足您的要求:
/// < 摘要 >
///
// / < / summary >
/// < param name =dateTime > 输入日期格式:ddd MMM d HH:mm:ss yyyy< / param >
/// < span class =code-comment> < 返回 > 输出日期格式:yyyy-MM-dd HH:mm:ss< /返回 >
private 串 ParseDateTime( string dateTime)
{
DateTime dateValue;
string UTC_DateTime = ;
尝试
{
// 8月9日00:00:03 2016 | 2016-08-09 00:00:03
dateValue = DateTime.ParseExact(dateTime, ddd MMM d HH:mm:ss yyyy,CultureInfo.InvariantCulture);
UTC_DateTime = dateValue.ToString( yyyy-MM-dd HH:mm:ss );
return UTC_DateTime;
}
catch (例外情况)
{
return ;
}
}
Hi,
I need to convert the date time format : 'Tue Aug 9 00:00:03 2016
' to '2016-08-09 00:00:03
'. I tried this below solution,but didn't work out. Please help me for the conversion to 'yyyy-MM-dd HH:mm:ss
' format. Thanks in advance.
What I have tried:
private string ParseDateTime(string dateTime)
{
try
{
DateTime dateValue; string UTC_DateTime = "";
if (DateTime.TryParse(dateTime, out dateValue))
{
UTC_DateTime = dateValue.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
}
else
{
var date = DateTime.ParseExact(dateTime, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.GetCultureInfo("en-us"));
UTC_DateTime = date.ToString("yyyy-MM-dd HH:mm:ss");
}
return UTC_DateTime;
}
catch (Exception ex)
{
return "";
}
}
First of all: a 'Tue Aug 9 00:00:03 2016
' date cannot be converted into '2016-10-09 00:00:03
', because due to August is 8. month in the year.
Second of all, all what you need to do is:
string inputDate = "Tue Aug 9 00:00:03 2016"; string inputFormat = "ddd MMM d hh:mm:ss yyyy"; System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-US"); DateTime resultDate = DateTime.ParseExact(inputDate, inputFormat, provider); //resultDate = '2016-08-09 00:00:03'
But(!), i'd suggest to use DateTime.TryParse[^] or DateTime.TryParseExact[^] method.
DateTime resultDate1; if (DateTime.TryParseExact(inputDate, inputFormat, provider, System.Globalization.DateTimeStyles.None, out resultDate1)) { Console.WriteLine("A result date is '{0}'", resultDate1); } else { Console.WriteLine("String to date conversion failed!"); }
[EDIT]
UsingDateTime.TryParseExact
, you can loop through the set of formats, ie.:
string inputDate = "Tue Aug 10 00:00:03 2016"; //'2016-10-09 00:00:03'. string[] inputFormats = new string[] {"MMM d hh:mm:ss yyyy", "MMM dd hh:mm:ss yyyy"}; System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-US"); DateTime resultDate = new DateTime(1900,1,1); foreach(string format in inputFormats) { if (DateTime.TryParseExact(inputDate.Substring(4,inputDate.Length-4), format, provider, System.Globalization.DateTimeStyles.None, out resultDate)) { Console.WriteLine("A result date is '{0}'", resultDate); break; } } if(resultDate==new DateTime(1,1,1)) { Console.WriteLine("String to date conversion failed. Unknown format!"); }
Add these lines,
private static string ParseDateTime(string dateTime) { var parts = dateTime.Split(' '); var day = parts[2]; var validDay = day.Length == 1 ? "0" + day : day; dateTime = dateTime.Replace(" " + day + " ", " " + validDay + " "); try {
The day you are passing is in"d"
format, but you are parsing in"dd"
format, so it has to be well formatted todd
for single digit numbers by adding0
atprefix
A very simple method for your requirement :
/// <summary> /// /// </summary> /// <param name="dateTime">input date format : "ddd MMM d HH:mm:ss yyyy"</param> /// <returns>output date format : "yyyy-MM-dd HH:mm:ss"</returns> private string ParseDateTime(string dateTime) { DateTime dateValue; string UTC_DateTime = ""; try { //Tue Aug 9 00:00:03 2016 | 2016-08-09 00:00:03 dateValue = DateTime.ParseExact(dateTime, "ddd MMM d HH:mm:ss yyyy", CultureInfo.InvariantCulture); UTC_DateTime = dateValue.ToString("yyyy-MM-dd HH:mm:ss"); return UTC_DateTime; } catch (Exception ex) { return ""; } }
这篇关于在C#中将字符串转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!