C# c中datetime的区域性#
嗨,我已经写了一段代码来解析datetime,如下所示C# c中datetime的区域性#,c#,asp.net,datetime,C#,Asp.net,Datetime,嗨,我已经写了一段代码来解析datetime,如下所示 if (DateTime.TryParse(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(), out _dtVoucherDate)) _dtVoucherDate = Convert.ToDateTime(dsVchRecord.Tables[0].Rows[0]["Date"].ToString()); else _dtVoucherDate = DateTime.Par
if (DateTime.TryParse(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(), out _dtVoucherDate))
_dtVoucherDate = Convert.ToDateTime(dsVchRecord.Tables[0].Rows[0]["Date"].ToString());
else
_dtVoucherDate = DateTime.ParseExact(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(), "MM-dd-yyyy", CultureInfo.InvariantCulture);
这在我的系统中运行良好,因为我当前的日期时间格式是
MM/DD/YYYY
,但在我的同事系统中,日期时间格式不同2013年6月15日
,因此我的代码在那里失败。如何将日期转换为通用格式,而不考虑系统日期或其他日期使用DateTime.TryParseExact
:
if (DateTime.TryParseExact(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(),
"MM/dd/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out _dtVoucherDate))
//the rest of it
var str = dsVchRecord.Tables[0].Rows[0].Field<String>("Date");
var allowedFormats = new[] { "MM-dd-yyyy", "dd MMM yyyy" };
_dtVoucherDate = DateTime.ParseExact(str, allowedFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);
第一次使用CultureInfo.InvariantCulture解析日期时间
DateTime dt = DateTime.Parse(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(), CultureInfo.InvariantCulture)
那就看看现在的文化吧
CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
然后将DateTime对象传递到当前区域性
dt = DateTime.Parse(dt.ToString(cultureInfo))
不可能处理所有格式,但可以为
ParseExact
指定多个允许的格式:
if (DateTime.TryParseExact(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(),
"MM/dd/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out _dtVoucherDate))
//the rest of it
var str = dsVchRecord.Tables[0].Rows[0].Field<String>("Date");
var allowedFormats = new[] { "MM-dd-yyyy", "dd MMM yyyy" };
_dtVoucherDate = DateTime.ParseExact(str, allowedFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);
如果
数据表
中的列类型已经是日期时间
,请不要将其转换为字符串
,然后再转换回日期时间
。相反,请使用强类型扩展方法:dsVchRecord.Tables[0]。Rows[0]。Field(“Date”)
无论您做什么,都不要错误地将日期解析为一种格式,如果第一种格式失败,请尝试另一种格式。这将是非常糟糕的,因为日数为12或更少的日期将变得不明确,wrt dd/mm/yyyy和mm/dd/yyyy格式。这不是OP在其ParseExact
方法中使用的格式。@TimSchmelter哇,对不起。修正了。你是说先用不变的区域性进行解析,然后如果解析失败,尝试用当前区域性进行解析吗?