开发者

Reading Dates correctly regardless of format

开发者 https://www.devze.com 2023-03-26 19:02 出处:网络
Is there a way to read date time correctly regardless of date format (e.g. en-AU and en-US) in C# 4.0 or whatever framework version?

Is there a way to read date time correctly regardless of date format (e.g. en-AU and en-US) in C# 4.0 or whatever framework version?

Below is two different date formats (top row is Australian format, bottom row is US format):

Timestamp,Windows User,Computer,Product,Version,Id,User,Action 
5/04/2011 9:14:16 AM,terryg,KETTSAM51,powerfulSoftware,3.0,0,Garry Terr开发者_如何学Goy,Lock
5/1/2011 12:38:22 PM,weanern,KETTSAM51,powerfulSoftware,3.0,1,Admin,Lock

What I want is to be able to read the dates, and process them all as Australian formatted dates.


string australiaCultureString = "en-AU";

CultureInfo australiaCulture = new CultureInfo(australiaCultureString);

To read as Australian culture:

DateTime time = DateTime.Parse(inputString, australiaCulture);

To represents Australian date time when call ToString()

string timeString = time.ToString(australiaCulture);


I don't see a way you could do it, for example, how should this parse:

08/01/2010

That's a valid date in both US and AU formats, so there will always be ambiguity unless you give the parser an extra hint.


No, you have to know the culture when parsing a date string.

For example,

 DateTime.Parse(dateString, new CultureInfo("en-US", false));

would parse the US date for you, but not the Australian date (unless both cultures happen to use the same date format, of course).

0

精彩评论

暂无评论...
验证码 换一张
取 消