[英]culture for datetime in c#
Hi all I have written a code to parse datetime as follows 大家好,我编写了如下代码来解析日期时间
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);
Which works fine in my system as my current datetime format is MM/DD/YYYY
, but in my colleague system the datetime format is different 15 June 2013
so my code fails there. 在我的系统中可以正常工作,因为我当前的日期时间格式为MM/DD/YYYY
,但是在我的同事系统中,日期时间格式与15 June 2013
不同,因此我的代码在此处失败。 How can I convert the date to a universal format irrespective of the system date or some other 如何将日期转换为通用格式,而不考虑系统日期或其他日期
It's not possible to handle all formats, but you can speicify multiple allowed formats for ParseExact
: 不可能处理所有格式,但是您可以为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);
Note : If the type of the column in the DataTable
is already DateTime
don't convert it to string
and then back to DateTime
. 注意 :如果DataTable
中的列类型已经是DateTime
请不要将其转换为string
,然后再转换回DateTime
。 Instead use the strongly typed Field
extension method: 而是使用强类型Field
扩展方法:
dsVchRecord.Tables[0].Rows[0].Field<DateTime>("Date")
Use DateTime.TryParseExact
: 使用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
First parse Datetime with CultureInfo.InvariantCulture 首先使用CultureInfo.InvariantCulture解析Datetime
DateTime dt = DateTime.Parse(dsVchRecord.Tables[0].Rows[0]["Date"].ToString(), CultureInfo.InvariantCulture)
then Get Current Culture 然后了解当前的文化
CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
then pass DateTime Object into current culture 然后将DateTime对象传递到当前区域性
dt = DateTime.Parse(dt.ToString(cultureInfo))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.