0

i am using the date.parse function to format the date input in the textbox. However if I input a future date the date parse function fails. Why is it so? I need to format the date and also input future dates.

  If IsDate(TransactionDate.Text) Then
            TransactionDate.Text = Date.Parse(TransactionDate.Text)
        Else
            MsgBox("Enter correct Transaction date")
            TransactionDate.Focus()
        End If
4

3 回答 3

0

i used 12/5/2013 and it worked fine.

I suspect it didn't, actually. I suspect it actually parsed it as December 5th 2013, when you meant May 12th 2013.

It seems that it's trying to parse it as a format of MM/dd/yyyy, whereas you mean dd/MM/yyyy.

That could be because the thread you're using is in a US culture, for example.

I suggest that you use DateTime.TryParseExact:

  • If you want to specify a precise format, you can do that using a custom date/time format pattern
  • If you want to allow .NET to use an appropriate format for the culture, you can do that using a standard date/time format pattern
  • Specify the culture you want to use for parsing, using CultureInfo.InvariantCulture if it's meant to parse machine-generated text. You can use null to mean "the culture of the currently executing thread" but personally I'd make that explicit, for readability
  • Use the return value to determine whether parsing failed. If this indicates a bug somewhere, then it would make sense to use DateTime.ParseExact instead, as that will throw an exception. Basically you need to work out what you want to do on error.
于 2013-05-12T11:21:14.760 回答
0

You need to specify the format you are expecting the data string to be in. Dates can be written in many formats - US (mm/dd/yyyy) or European (dd/mm/yyyy), two digit years (yy) or four digit years (yyyy), different separator (/) vs (-) and so on. The list is endless.

You either need to state explicitly what date you expect or write your code to try various formats and cope with incorrect inputs.

The danger with the latter approach is that dates can be ambiguous - is "1/2/2013" the 1st of February or the 2nd of January?

Use an overload of Date.TryParse that takes an IFormatProvider and report an error if it fails.

dateString = "2008-03-01 10:00"
culture = CultureInfo.CreateSpecificCulture("fr-FR")
styles = DateTimeStyles.AdjustToUniversal Or DateTimeStyles.AssumeLocal
If DateTime.TryParse(dateString, culture, styles, dateResult)
   Console.WriteLine("{0} converted to {1} {2}.", _
                     dateString, dateResult, dateResult.Kind)
Else
   Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
End If
于 2013-05-12T11:21:31.330 回答
0

Use DateTime.ParseExact and pass the format and provide.

dateString = "13/05/2013";
  format = "dd-MM-yyyy";
  CultureInfo provider = CultureInfo.InvariantCulture;
  var result = DateTime.ParseExact(dateString, format, provider);
于 2013-05-12T11:25:40.267 回答