无论DateTime格式如何,字符串到日期时间

时间:2013-12-14 16:28:31

标签: c# .net winforms datetime

我有一个文本文件,其中DateTimes存储如下:30/11/2013 1:18:36 PM

如果您只在一台计算机上运行程序,这很好,因为DateTime的存储格式与系统使用的格式相同。但是我刚遇到一个问题,如果我将用户更改为我的其他帐户之一,由于某种原因使用MM / DD / YYYY格式,则会引发错误。无论系统格式是什么,我如何阅读DateTime?这就是我现在正在使用的:

RecieptList.Add(new Reciept
                {
                    ...
                    DateNTime = Convert.ToDateTime(stringArray[(i * 12) + 9]), // == 30/11/2013 1:18:36 PM
                    ...
                });

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用TryParseExact()来解析日期。

试试这个:

String dt = "30/11/2013 1:18:36 PM";//or anydate
DateTime result;
if (DateTime.TryParseExact(dt, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None,out result))
{
   //success use result
}

修改:根据您提到的评论,您将dates存储在系统dependent culture中。

我强烈建议您在存储日期时使用CultureInfo.InvarientCulture参数,以将其存储在Indepedent culture中。

这样在不同机器上阅读时不会产生问题。

尝试此操作:将Dates存储到TextFile

 String dt = DateObject.ToString(CultureInfo.InvariantCulture);

现在您可以将字符串dt写入TextFile

答案 1 :(得分:0)

您需要使用正确的计算机设置解析日期。您可以通过调用Thread.CurrentUICulture来获取UI设置。

CultureInfo ci = Thread.CurrentUICulture ; // ci refers to the current UI culture
Convert.ToDateTime(dateStr, ci);

用上面的代码替换你的代码,它应该工作。您可以在下面找到更多示例

Convert.ToDateTime Method (String, IFormatProvider)

DateTime.TryParse Method (String, IFormatProvider, DateTimeStyles, DateTime)

相关问题