Parsing date in different culture

痞子三分冷 提交于 2019-12-24 07:28:10

问题


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.



来源:https://stackoverflow.com/questions/12937256/parsing-date-in-different-culture

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!