c# - 字符串到日期时间转换失败

标签 c# .net winforms datetime type-conversion

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

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);

最佳答案

您的字符串在该系统上不是固定区域性中的有效日期:26/10/2013 11:58:03 AM。不变文化需要月/日/年,而不是日/月/年。

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


Edit: Why won't this work to convert current time to the right culture?

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

在您的情况下,我建议始终使用相同的文化进行读写 - 如果您使用以下方式编写文件:theDate.ToString(CultureInfo.InvariantCulture),那么您可以使用 进行阅读Convert.ToDateTime(theString, CultureInfo.InvariantCulture),它可以在任何系统上运行,因为相同的规则(不变区域性)用于写入和读取。

关于c# - 字符串到日期时间转换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19776206/

相关文章:

c# - 将位图和 Png 图像转换为文本的简单方法,反之亦然

C# - 在一个字符串中存储多个值

.net - 与证书战斗 : Access was not successfully obtained for the private key

c# - 在 GeckoWebBrowser 中检索选定的文本

c# - ASP.NET MVC 3 中的@Html.ActionLink

c# - 从基于 JSON/PHP (base64_encode) 的图像中解释 C# 中的 base 64

c# - Microsoft.Azure.Mobile 命名空间问题 [UWP]

c# - 删除按钮的文本轮廓

c# - System.Security.Principal.WindowsIdentity 和 WinForms 身份验证

winforms - System.Windows.Threading.Dispatcher 和 WinForms?