Format exception String was not recognized as a va

2019-09-12 11:49发布

问题:

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)