4

我正在尝试将字符串从文本文件转换为 DateTime,但我得到了奇怪的结果。在一台计算机上,它可以工作,但在另一台计算机上却不行。我将如何在所有计算机上进行这项工作?在我的最后一个问题上,您说要添加文化的东西,它工作了几分钟,但现在它不再工作了。这是我的代码:

string[] stringArray = File.ReadAllLines("C:\\Program Files\\PointOfSales\\RecordTotals.txt");
            int lines = stringArray.Length;

            for (int i = 0; i < (lines / 5); i++)
            {
                TransactionList.Add(new Transaction
                {
                    TotalEarned = Convert.ToDouble(stringArray[(i * 5)]),
                    TotalCost = Convert.ToDouble(stringArray[(i * 5) + 1]),
                    TotalHST = Convert.ToDouble(stringArray[(i * 5) + 2]),
                    Category = stringArray[(i * 5) + 3],
                    HoursSince2013 = Convert.ToDateTime(stringArray[(i * 5) + 4], CultureInfo.InvariantCulture)
                });
            }

我收到错误String was not recognized as a valid DateTime.

有什么线索吗?谢谢!

编辑:使用MessageBox.Show(stringArray[(i * 5) + 4]);我得到26/10/2013 11:58:03 AM

编辑:为什么不能将当前时间转换为正确的文化?

DateTime Today = DateTime.Now;
            Today = DateTime.ParseExact(Today.ToString(), "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
4

2 回答 2

1

您在该系统上的字符串不是不变文化中的有效日期:26/10/2013 11:58:03 AM. 不变的文化期望月/日/年,而不是日/月/年。

您应该指定用于生成您正在阅读的文件的相同区域性。您将需要有某种方法来确定或标准化用于写入文件和读取文件的文化。


编辑:为什么不能将当前时间转换为正确的文化?

如果您当前的文化不使用dd/MM/yyyy它的格式,那将失败。 Today.ToString()没有指定文化或格式,因此在美国系统上,它将使用MM/dd/yyyy格式写出,这将导致调用失败。

在您的情况下,我建议始终使用相同的文化进行读写 - 如果您使用 : 编写文件 theDate.ToString(CultureInfo.InvariantCulture),那么您可以使用 读取Convert.ToDateTime(theString, CultureInfo.InvariantCulture),并且它适用于任何系统,因为两者都使用相同的规则(不变文化)写作和阅读。

于 2013-11-04T20:14:50.667 回答
0

You should use custom "dd/MM/yyyy HH:mm:ss t" format with InvariantCulture like;

string s = "26/10/2013 11:58:03 AM";
DateTime dt = DateTime.ParseExact(s, "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
Console.WriteLine(dt);

Output will be;

10/26/2013 11:58:03 AM

Here a demonstration.

For more information, take a look at;

EDIT: If your DateTime.Now doesn't fit "dd/MM/yyyy HH:mm:ss tt" format, your program will fail. You should use InvariantCulture in all your programs with your DateTime.Now format exactly.

于 2013-11-04T20:16:58.080 回答