0

input value ="3:10 PM" or "15:10" depend on regional settings in control panel. when set to India input value is "15:10" and when set to US input value is "3:10 PM". I have to convert input value to "1899-12-30 15:10:00.000" every time for that written below code but while parsing its showing error "String was not recognized as a valid Date Time".

 Private Function GetCurrentTime(ByVal value As String) As DateTime
        Dim oaDate As DateTime
        Dim timeValue As DateTime

        oaDate = DateTime.FromOADate(0)
        value = String.Concat(oaDate.Year, oaDate.Month, oaDate.Day, value)
        timeValue = DateTime.ParseExact(value, "yyyyMMddHH:mm", Globalization.CultureInfo.InvariantCulture)
        Return timeValue

    End Function
sstan
  • 35,425
  • 6
  • 48
  • 66
ND's
  • 2,155
  • 6
  • 38
  • 59

1 Answers1

0

If you're input can be different depending on the culture then you can't use the following line to parse the string:

timeValue = DateTime.ParseExact(value, "yyyyMMddHH:mm", Globalization.CultureInfo.InvariantCulture)

as you've got a single fixed format and you are specifying an invariant culture.

If the input might be invalid you should either trap the exception and display a suitable error message or use TryParseExact and display a suitable error message if that returns false.

You must either check the current culture and call either your current code or the code for the US, or test each possible format in turn using TryParseExact until you find one that produces a valid date. There is an overload of TryParseExact that takes a list of format strings so you can do the check in on go. You'd need something like this (apologies for the C# syntax):

string[] formats = {"yyyyMMddHH:mm", "yyyyMMddh:mm"};
DateTime result
if (TryParseExact(value, formats, ..., out result))
{
    // use the result
}
else
{
    // invalid input
}

However, (and this is a big however), you could get the situation where the input could be valid in more than one culture you could end up with the wrong result.

ChrisF
  • 134,786
  • 31
  • 255
  • 325