以文化中性格式存储日期时间 + C#

San*_*pku 0 .net c# datetime date datepicker

我通过日期选择器接受来自用户的日期信息。我需要以文化中立的方式存储它们。我面临的问题是,如果我按照 en-US 格式(基于日历设置)存储日期,即 11/20/1990,当文化为 en-GB 时,它将无法解析。

反之亦然,当文化为 en-US、日期按英国格式存储、dd/mm/yyyy 拒绝解析时。如何以文化中立的方式将日期信息存储在文件中,以便获得在两个位置工作的日期?

DateTime.TryParse(userEnteredValue, out result);
result.ToShortDateString(); //this is what I am doing 
Run Code Online (Sandbox Code Playgroud)

为不变文化尝试了此代码

string input = "20/10/1983";
DateTime userInput;

bool result = DateTime.TryParse(input, out userInput);

string invariantCulture = userInput.Date.ToString(CultureInfo.InvariantCulture);

DateTime storedValue;

result = DateTime.TryParse(invariantCulture, out storedValue);
Run Code Online (Sandbox Code Playgroud)

使用 en-GB 日历设置尝试了此代码,第二个语句 DateTime.TryParse 实际上失败了。

pet*_*ids 5

如果您将日期保存到数据库中,@Soner Gönül 的答案是正确的。不过,你提到你正在寻找往返一个DateTime和从文件

由于该文件可能是一个文本文件,您需要以DateTime文化中立的方式编写。您可以使用方法中指定的“O”格式来完成此操作DateTime.ToString。这将输出符合 ISO 8601 的字符串表示形式。结果字符串可以DateTime.Parse在不需要区域性信息的情况下进行解析。

举个例子:

string filename = @"c:\temp\test.txt";
string usDateString = "11/18/2014 12:32"; // MM/dd/yyyy
string ukDateString = "18/11/2014 12:33"; // dd/MM/yyyy

//I'm mimicking you getting the DateTime from the user here    
//I'm assuming when you receive the date(s) from the front
//end you'll know the culture - if not then all bets are off. 
DateTime usDate = 
      DateTime.Parse(usDateString, CultureInfo.GetCultureInfo("en-US"));
DateTime ukDate = 
      DateTime.Parse(ukDateString, CultureInfo.GetCultureInfo("en-GB"));

//write the dates to a file using the "o" specifier
File.AppendAllText(filename, usDate.ToString("o") + Environment.NewLine);
File.AppendAllText(filename, ukDate.ToString("o") + Environment.NewLine);

//read them back in as strings
string[] contents = File.ReadAllLines(filename);
        
foreach (var date in contents)
{
    //prove we can parse them as dates.
    Console.WriteLine(DateTime.Parse(date).ToString());
}
Run Code Online (Sandbox Code Playgroud)

这将创建一个包含以下内容的文件:

2014-11-18T12:32:00.0000000

2014-11-18T12:33:00.0000000

在我的系统上(在英国)它打印:

18/11/2014 12:32:00

18/11/2014 12:33:00