Parsing date in different culture

2019-08-06 11:57发布

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....

标签: c# locale
2条回答
地球回转人心会变
2楼-- · 2019-08-06 12:15

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.

查看更多
Evening l夕情丶
3楼-- · 2019-08-06 12:21

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);
查看更多
登录 后发表回答