[英]culture for datetime in c#
大家好,我編寫了如下代碼來解析日期時間
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
,但是在我的同事系統中,日期時間格式與15 June 2013
不同,因此我的代碼在此處失敗。 如何將日期轉換為通用格式,而不考慮系統日期或其他日期
不可能處理所有格式,但是您可以為ParseExact
指定多種允許的格式:
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);
注意 :如果DataTable
中的列類型已經是DateTime
請不要將其轉換為string
,然后再轉換回DateTime
。 而是使用強類型Field
擴展方法:
dsVchRecord.Tables[0].Rows[0].Field<DateTime>("Date")
使用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
首先使用CultureInfo.InvariantCulture解析Datetime
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.