格式异常字符串未被识别为有效的DateTime [英] Format exception String was not recognized as a valid DateTime

查看:86
本文介绍了格式异常字符串未被识别为有效的DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

objTour.tourStartDate = 
    Convert.ToDateTime(
        DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", null)
            .ToString("MM/dd/yyyy"));

其中 txtTourStartDate.Text = 2012/08/16

我已经搜索并阅读了与此相关的所有帖子。

I have searched and read all posts related to this.

推荐答案

自定义日期格式字符串中, / 表示区域性特定的日期分隔符,而不是文字字符 / 。因此,代码的结果取决于用户(或服务器)的本地化设置。

In a custom date format string, / denotes the culture-specific date separator, not the literal character /. Thus, the result of your code depends on the user's (or the server's) localization settings.

要使代码独立于特定于文化的设置,您有两个选择:

To make your code independent of culture-specific settings, you have two options:


  • 明确指定使用斜杠作为日期分隔符的区域,例如

  • Explicitly specify a culture that uses a slash as the date separator, e.g.

DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", 
                    CultureInfo.InvariantCulture)


  • 或转义字符,例如

  • or escape the character, e.g.

    DateTime.ParseExact(txtTourStartDate.Text, @"dd\/MM\/yyyy", null)
    

    (请注意 @ \ )。

    两者都应产生预期的结果。

    Both should yield the desired result.

    这篇关于格式异常字符串未被识别为有效的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆