简体   繁体   English

在不同文化中解析日期

[英]Parsing date in different culture

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 . 并适用于像Sat,Sep 8,2012这样的字符串。
But when my software is used on customer pc, he gets the error 但是当我的软件在客户PC上使用时,他得到了错误

String was not recognized as a valid DateTime 字符串未被识别为有效的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.... 这就是我决定使用我编写的代码的原因。

You might want to have a look at DateTime.ParseExact 您可能想看看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);

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. 对于以您的字符串格式抛出的字符串,它似乎对我有用,但是我没有用不同的文化对其进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM