我需要将日期时间转换为en-us文化格式…
但是我们的用户在不同的地方;有些人遵循
DD.MM。YYYY hh:mm:ss tt,
我得到一个错误
"字符串未被识别为有效DateTime "
转换
时区到MM/DD/YYYY hh: MM:ss tt(en - us)。
System.Globalization.CultureInfo oCulture = new System.Globalization.CultureInfo("en-US", false);
public string CultureStringFormat(string Date)
{
DateTime _Datetime = DateTime.Now;
try
{
_Datetime = DateTime.Parse(Date);
return _Datetime.ToString("G", oCulture);
}
catch (Exception ex)
{
try
{
_Datetime = DateTime.Parse(Date, oCulture);
return _Datetime.ToString("G", oCulture);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
return "";
}
public DateTime CultureDateFormat(string Date)
{
try
{
return DateTime.Parse(Date, oCulture, DateTimeStyles.NoCurrentDateDefault);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return DateTime.Now;
}
Thread.CurrentThread.CurrentCulture = oCulture;
string sDate = CultureStringFormat("28.12.2011 10:15:07"); // i'm getting an Error
DateTime dtDate = CultureDateFormat("28.12.2011 10:15:07"); // Error
string sDate1 = CultureStringFormat("12.27.2011 10:15:07"); // i'm getting success 12/27/2011 10:15:07 AM
DateTime dtDate1 = CultureDateFormat("12.27.2011 10:15:07"); //success 12/27/2011 10:15:07 AM
Thread.CurrentThread.CurrentCulture = oCulture; //Without this line ...
string sDate = CultureStringFormat("28.12.2011 10:15:07"); // success 12/28/2011 10:15:07 AM
DateTime dtDate = CultureDateFormat("28.12.2011 10:15:07"); // Error
string sDate1 = CultureStringFormat("12.27.2011 10:15:07");// success 12/27/2011 10:15:07 AM
DateTime dtDate1 = CultureDateFormat("12.27.2011 10:15:07");// Wrong 27.12.2011 10:15:07
您需要使用DateTime.TryParseExact
。下面的代码片段应该能让你朝着正确的方向开始:
string myDate = "17.11.2011 08:00:00 AM";
DateTime parsedDate;
DateTime.TryParseExact(myDate,
"dd.MM.yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out parsedDate);
public DateTime? GetDate(string dateString)
{
var formats = new string[]
{
"dd.MM.yyyy hh:mm:ss",
"MM/dd/yyyy hh:mm:ss",
"dd.MM.yyyy HH:mm:ss",
"MM/dd/yyyy HH:mm:ss",
"dd.MM.yyyy hh:mm:ss tt",
"MM/dd/yyyy hh:mm:ss tt"
};
DateTime date;
if ( DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out date))
{
return date;
}
return null;
}