简体   繁体   English

Convert.ToDateTime() 错误

[英]Convert.ToDateTime() error

I get an error trying to convert a string to DateTime , even though this has always worked before.尝试将string转换为DateTime出现错误,即使这以前一直有效。

This is the procedure I used:这是我使用的程序:

  1. Save a datetime to a text file like this:将日期时间保存到文本文件中,如下所示:

     DateTime.Now.ToUniversalTime().ToString(); //results in something like this 20.9.2015 10.16.12
  2. On application load up:在应用程序加载时:

     string s = streamReader.ReadLine(); //the saved string s = "20.09.2015 10.16.12" DateTime d = Convert.ToDateTime(s);

This results in this:这导致:

String was not recognized as a valid DateTime.字符串未被识别为有效的 DateTime。

I have never experienced this problem before I installed Windows 10 and Visual Studio 2015, my previous setup was Windows 7 and Visual Studio 2013. The weird thing is that this also results in the same error:我在安装 Windows 10 和 Visual Studio 2015 之前从未遇到过这个问题,我之前的设置是 Windows 7 和 Visual Studio 2013。奇怪的是,这也会导致同样的错误:

DateTime d = Convert.ToDateTime(DateTime.Now.ToUniversalTime().ToString());

This did work perfectly in my previous setup, any ideas why it does not work any more?这在我以前的设置中确实工作得很好,有什么想法为什么它不再工作了吗?

Edit: I do believe that this question is not a duplicate of the question Converting a String to DateTime that Thomas Weller linked to.编辑:我确实相信这个问题不是 Thomas Weller 链接到的将字符串转换为日期时间的问题的重复。 Because this problem is the result of changes in expected behaviour, see the second example.因为此问题是预期行为变化的结果,请参阅第二个示例。 Also I did find a fix to this, but it is not practical:我也确实找到了解决方法,但这并不实用:

    string s = DateTime.Now.ToUniversalTime().ToString(); 
    s = s.Substring(0, s.IndexOf(" ")).Replace('.', '/') + s.Substring(s.IndexOf(" ")).Replace('.', ':'); 
    DateTime d = Convert.ToDateTime(s);

This probably does not work anymore due to your regional settings on control panel.由于您在控制面板上的区域设置,这可能不再起作用。

To avoid conflicts with regional settings on target enviroment, use DateTime.TryParseExact :为避免与目标环境中的区域设置发生冲突,请使用DateTime.TryParseExact

string s = streamReader.ReadLine(); //the saved string s = "20.09.2015 10.16.12"
DateTime d = DateTime.Now;
DateTime.TryParseExact(s, "dd.MM.yyyy HH.mm.ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);

Also, if this is your default format and you need this format for entire application, you can set the default culture on your config file .此外,如果这是您的默认格式,并且整个应用程序都需要这种格式, 您可以在配置文件中设置默认文化

This code:这段代码:

Convert.ToDateTime(DateTime.Now.ToUniversalTime().ToString())

Should work on any enviroment, once that DateTime.ToString() and Convert.ToDateTime() without a format provider uses the same DateTimeFormatInfo, unless you are changing your culture between these calls.一旦没有格式提供程序的 DateTime.ToString() 和 Convert.ToDateTime() 使用相同的 DateTimeFormatInfo ,则应该适用于任何环境,除非您在这些调用之间改变了您的文化。 Note that DateTime.ToString() without format specifier will use General date/time pattern (G) , that is based on current culture .请注意,没有格式说明符的 DateTime.ToString() 将使用基于当前文化的通用日期/时间模式 (G) And Convert.DateTime without FormatProvider will use current culture too (check these references on MSDN).没有 FormatProvider 的 Convert.DateTime 也将使用当前文化(在 MSDN 上查看这些参考资料)。

My last suggestion is, instead of doing replaces, you can do:我的最后一个建议是,您可以执行以下操作,而不是进行替换:

string s = DateTime.Now.ToUniversalTime().ToString("dd/MM/yyyy HH:mm:ss");

I tried following code in console application, and it worked for me.我在控制台应用程序中尝试了以下代码,它对我有用。 And check .NETFiddle here在此处检查 .NETFiddle

string s = "20.09.2015 10.16.12";
DateTime d;
bool isValid = DateTime.TryParseExact(s, "dd.MM.yyyy HH.mm.ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);

Try to understand how TryParseExact works.尝试了解 TryParseExact 的工作原理。 You can read about TryParseExact and formats here .您可以在此处阅读有关TryParseExact和格式的信息 It return a true if it successfully converts the value, else it returns a false .它返回一个true ,如果它成功地转换值,否则返回一个false

Please try with this.请试试这个。

CultureInfo objcul = new CultureInfo("en-GB"); CultureInfo objcul = new CultureInfo("en-GB");

DateTime.ParseExact(ValidFrom.Text,"dd/MM/yyyy", objcul); DateTime.ParseExact(ValidFrom.Text,"dd/MM/yyyy", objcul);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM