简体   繁体   English

更改机器时间格式时,无法将字符串识别为有效的DateTime。

[英]String was not recognized as a valid DateTime when machine time format is changed.

I have a Date string in format dd/MM/yyyy I am string to get this string in 'yyyyMMdd' So I tried : 我有一个格式为dd/MM/yyyy的Date字符串,我是要以'yyyyMMdd'形式获取此字符串的字符串,所以我尝试了:

todate1 = Convert.ToDateTime(txttdate.Text).ToString("yyyyMMdd")

and it worked fine when my local machine time was in format dd/MM/yyyy but then when I change the system time format it stops working it gives me error 当我的本地机器时间格式为dd/MM/yyyy时,它工作正常,但是当我更改系统时间格式时,它停止工作,这给了我错误

String was not recognized as a valid DateTime 

How do solve this problem? 如何解决这个问题? I need to convert dd/MM/yyyy string to yyyyMMdd 我需要将dd/MM/yyyy字符串转换为yyyyMMdd

Use DateTime.ParseExact instead of Convert.ToDateTime and specify the pattern and InvariantCulture as format provider: 使用DateTime.ParseExact而不是Convert.ToDateTime并指定模式和InvariantCulture作为格式提供者:

var todate1 = DateTime.ParseExact(@"05/12/2013", @"dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("yyyyMMdd");

It should prevent your code from failure on different culture settings. 这样可以防止您的代码在不同的区域性设置下失败。

Use ParseExact and specifiy CultureInfo.InvariantCulture : 使用ParseExact并指定CultureInfo.InvariantCulture

DateTime todate1;

if (DateTime.TryParseExact(txttdate.Text, new[] { "dd/MM/yyyy" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out todate1)) {
    string yourNewFormat = todate1.ToString("yyyyMMdd");
}
else {
    // it failed
}

Using TryParseExact allows you to recover from potentially invalid dates being provided. 使用TryParseExact可使您从提供的潜在无效日期中恢复。

I had a similar problem in my web application, tried many things like above but nothing helped me. 我在Web应用程序中遇到了类似的问题,尝试了上述类似的许多操作,但没有任何帮助。 But when I added globalization tag in my config file it worked like a charm. 但是,当我在配置文件中添加全球化标记时,它就像一个符咒。

    <system.web>
      <globalization requestEncoding="UTF-8" responseEncoding="UTF-8" uiCulture="en-GB" culture="en-GB" />
    </system.web>

change culture to US or IN or whatever u want. 将文化更改为美国或印度或您想要的任何内容。

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

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