Format exception String was not recognized as a valid DateTime

笑着哭i 提交于 2019-12-12 03:49:25

问题


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

where txtTourStartDate.Text="16/08/2012".

I have searched and read all posts related to this.


回答1:


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)
    

    (note the @ and the \).

Both should yield the desired result.




回答2:


This will be enough:

objTour.tourStartDate = DateTime.ParseExact(txtTourStartDate.Text, 
                                            "dd/MM/yyyy", 
                                            CultureInfo.InvariantCulture);



回答3:


Your original code works, although you are doing lot of unnecessary conversions. (DateTime -> ToString -> ToDateTime), the real issue is InvariantCulture. Since you are passing null for CultureInfo try CultureInfo.InvariantCulture.

Your original code:

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

A better one could be:

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


来源:https://stackoverflow.com/questions/12209436/format-exception-string-was-not-recognized-as-a-valid-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!