C# 日期时间和文化信息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13797727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:49:50  来源:igfitidea点击:

DateTime and CultureInfo

c#datetimecultureinfo

提问by petko_stankoski

I have this in my code:

我的代码中有这个:

var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

And when my current cultur is dutch (nl-NL) instead of May 1st I get January 5th.

当我目前的文化是荷兰语 ( nl-NL) 而不是 5 月 1 日时,我会得到 1 月 5 日。

I think the error is in the second parameter dd.MM.yyyy HH:mm:ss.

我认为错误在第二个参数中dd.MM.yyyy HH:mm:ss

Is there a way to fix this using the CultureInfoclass?

有没有办法使用CultureInfo类来解决这个问题?

采纳答案by MMK

You may try the following:

您可以尝试以下操作:

System.Globalization.CultureInfo cultureinfo =
        new System.Globalization.CultureInfo("nl-NL");
DateTime dt = DateTime.Parse(date, cultureinfo);

回答by Tim Schmelter

InvariantCultureis similar to en-US, so i would use the correct CultureInfoinstead:

InvariantCulture类似于en-US,所以我会改用正确的CultureInfo

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

演示

And what about when the culture is en-us? Will I have to code for every single language there is out there?

当文化是 en-us 时呢?我是否必须为现有的每种语言编写代码?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

如果您想知道如何在另一种文化中显示日期,例如“en-us”,您可以使用date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

回答by Soner G?nül

Use CultureInfoclass to change your culture info.

使用CultureInfo类来改变你的文化信息。

var dutchCultureInfo = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCultureInfo);