What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleSee if a date string is valid using regional date settings
Keywordsdate string, validate, validation, regional, international
CategoriesStrings, Tips and Tricks, Syntax
Thanks to Roger Gilchrist.

This version uses the GetLocaleInfo API function to get localization information so it verifies the correct data format.

Private Function InputDateFormat() As String
  'this creates the date format to check with Format in
  ' IsValidDate

  Select Case LocalDMY
   Case 0
    InputDateFormat = "m" & LocalDateDiv & "d" & _
        LocalDateDiv & "yy"
   Case 1
    InputDateFormat = "d" & LocalDateDiv & "m" & _
        LocalDateDiv & "yy"
   Case 2
    InputDateFormat = "yy" & LocalDateDiv & "m" & _
        LocalDateDiv & "d"
  End Select
End Function

Public Function IsValidDate(ByVal txt As String, _
                            Optional strFormat As String) _
                                As Boolean
  'internationalized version
  'Optionally returns the format that it recognised
  'otherwise for days whose number is < 12 you may not be
  ' sure
  'if 2/12/99 is 2nd December or 12th Febuary if you don't
  'know which system your machine is using

  strFormat = InputDateFormat
  On Error GoTo DoneChecking
  IsValidDate = (Format$(CDate(txt), strFormat) = txt)
  Exit Function

  strFormat = "INVALID DATE: " & txt & " Check format = " & _
End Function

Public Function LocalDateDiv() As String
  ' gets the local date divisor
  LocalDateDiv = LocalizationData(LOCALE_SDATE)
End Function

Public Function LocalDMY() As Integer
  'gets the D M Y order
  'Returns 0,1, or 2
  '0 Month-Day-Year
  '1 Day-Month-Year
  '2 Year-Month-Day

  LocalDMY = LocalizationData(LOCALE_ILDATE)
  'LocalDMY = LocalizationData(LOCALE_IDATE) would also work
  '(I can't imagine anyone uses different ones in a single
  ' local)
End Function

Public Function LocalizationData(ByVal LData As Long) As _
  'This is a general routine to read whatever bit of data
  'you want based on the constants fed to it as LData
  Dim stBuff As String * 255
  Dim Ret    As Long

  Ret = GetLocaleInfo(1024, LData, ByVal stBuff, _
  If Ret Then
    LocalizationData = Left$(stBuff, Ret - _
        IIf(StrConv(stBuff, vbFromUnicode) = stBuff, 0, 1))
    'NOTE the IIf bit of code determines whether you are
    ' dealing with an ASCII or UniCode system and
    'trims the string accordingly
  End If
End Function

Public Function LocalLongDate() As String
  LocalLongDate = LocalizationData(LOCALE_SLONGDATE)
End Function

Public Function LocalShortDate() As String
  LocalShortDate = LocalizationData(LOCALE_SSHORTDATE)
End Function
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.