Parsing date in different culture

2019-08-06 11:43发布

问题:

I'm developing a software that should be used from a US customer.
On my pc (italian) I use

CultureInfo cultureUS = CultureInfo.GetCultureInfo("en-US");
DateTime dt = DateTime.Parse(s, cultureUS);

and this works with a string like Sat, Sep 8, 2012.
But when my software is used on customer pc, he gets the error

String was not recognized as a valid DateTime

Why? What's wrong?
What should I use to let it work everywhere?

EDIT:
just to avoid confusion: I read those kind of dates both from web and files and I need to parse them and then use them (in that format) to write some other file.
So I thought I did not need to convert them to a "standard" format and then convert them back again: I'd like to use them from that format and write them directly to files...
And this is the reason I decided to use the code I wrote....

回答1:

You might want to have a look at DateTime.ParseExact

CultureInfo cultureInfo = CultureInfo.GetCultureInfo("en-US");
DateTime dateTime = DateTime.ParseExact(s, "D", cultureInfo);

edit

For exact time date format, you can try:

DateTime dateTime = DateTime.ParseExact(s, "ddd, MMM dd, yyyy", cultureInfo);


回答2:

I'm not used to localizations but perhaps this might work for you:

DateTime.Parse(date, new DateTimeFormatInfo()
                         { LongDatePattern = "ddd, MMM dd, YYYY" });

It appears to be working for me for the strings I've thrown at it in your string format, but I haven't tested it with varying cultures.



标签: c# locale