Developer
Developer

Reputation: 8646

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. How can I convert the date to a universal format irrespective of the system date or some other

Upvotes: 0

Views: 460

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460288

It's not possible to handle all formats, but you can speicify multiple allowed formats for 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. Instead use the strongly typed Field extension method:

dsVchRecord.Tables[0].Rows[0].Field<DateTime>("Date")

Upvotes: 1

Pankaj Agarwal
Pankaj Agarwal

Reputation: 11309

First parse Datetime with CultureInfo.InvariantCulture

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

dt = DateTime.Parse(dt.ToString(cultureInfo))

Upvotes: 0

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22814

Use 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

Upvotes: 0

Related Questions