我需要将datetime转换为en-us文化格式......
但我们的用户位于不同的地方;有些人关注
DD.MM.YYYY hh:mm:ss tt,
我收到错误
转换时“字符串未被识别为有效 日期时间“
时区到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
答案 0 :(得分:1)
您需要使用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);
答案 1 :(得分:1)
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;
}