繁体   English   中英

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

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

我有一个格式为dd/MM/yyyy的Date字符串,我是要以'yyyyMMdd'形式获取此字符串的字符串,所以我尝试了:

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

当我的本地机器时间格式为dd/MM/yyyy时,它工作正常,但是当我更改系统时间格式时,它停止工作,这给了我错误

String was not recognized as a valid DateTime 

如何解决这个问题? 我需要将dd/MM/yyyy字符串转换为yyyyMMdd

使用DateTime.ParseExact而不是Convert.ToDateTime并指定模式和InvariantCulture作为格式提供者:

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

这样可以防止您的代码在不同的区域性设置下失败。

使用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
}

使用TryParseExact可使您从提供的潜在无效日期中恢复。

我在Web应用程序中遇到了类似的问题,尝试了上述类似的许多操作,但没有任何帮助。 但是,当我在配置文件中添加全球化标记时,它就像一个符咒。

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

将文化更改为美国或印度或您想要的任何内容。

暂无
暂无

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

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