我有一个来自数据库的字符串11,111
现在我想检查一下,如果这个字符串是一个日期时间,然后将其解析为datetime但是如果不是,那么保持原样,但是DateTime.Parse正在解析它进入约会01/11/0111 12:00 AM
不正确 。这是我的代码
DateTime newDateTimeValue = default(DateTime);
DateTime.TryParse(each.NewValue, out newDateTimeValue);
if (newDateTimeValue != default(DateTime))
each.NewValue = Utility.FormatDate(DateTime.Parse(each.NewValue), dateFormat, culture);
这是FormatDate函数来自Utility Class
public static string FormatDate(DateTime? dt, string dateFormat, string language)
{
if (dt.HasValue)
{
string offset = string.Format("{0:0.00}", Convert.ToDouble(HttpContext.Current.Session["Offset"]));
string offsetSign = offset.Contains("-") ? "-" : string.Empty;
if (language == "en-US")
dt = dt.Value.AddHours(Convert.ToDouble(offset.Substring(0, offset.IndexOf('.')))).AddMinutes(Convert.ToDouble(offsetSign + offset.Substring(offset.IndexOf('.') + 1, offset.Length - offset.IndexOf('.') - 1)));
else
{
try
{
dt = dt.Value.AddHours(Convert.ToDouble(offset.Substring(0, offset.IndexOf(',')))).AddMinutes(Convert.ToDouble(offsetSign + offset.Substring(offset.IndexOf(',') + 1, offset.Length - offset.IndexOf(',') - 1)));
}
catch
{
dt = dt.Value.AddHours(Convert.ToDouble(offset.Substring(0, offset.IndexOf('.')))).AddMinutes(Convert.ToDouble(offsetSign + offset.Substring(offset.IndexOf('.') + 1, offset.Length - offset.IndexOf('.') - 1)));
}
}
dateFormat = dateFormat + " hh:mm tt";
if (dateFormat == "MMM dd, yyyy hh:mm tt" || dateFormat == "dd MMM yyyy hh:mm tt")
return dt.Value.ToString(dateFormat, new CultureInfo(language));
else
return dt.Value.ToString(dateFormat, new CultureInfo("en-US"));
}
else
return string.Empty;
}
答案 0 :(得分:0)
可以帮助别人
public void GetDate(string dateString)
{
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "d";
try
{
if(DateTime.TryParseExact(dateString,provider, DateTimeStyles.None, out result))
{
Console.WriteLine("{0} converts to {1}", dateString, result.ToString());
}
else
{
Console.WriteLine("{0} is not in the correct format", dateString);
}
}
catch(FormatException)
{
Console.WriteLine("{0} is not in the correct format", dateString);
}
}