You can use the built-in Format
function to do this for you.
Here is a simple test to confirm this:
Public Sub TestDateParsing()
'On my computer, the date format is U.S. (mm/dd/yyyy)'
'This test creates a date string in dd/mm/yyyy format to'
'simulate user input in a different format'
Const TEST_DATE As Date = #6/1/2009#
Dim inputDate As String
inputDate = Format(TEST_DATE, "dd/mm/yyyy")
'inputDate is "1/6/2009" (June 1 in dd/mm/yyyy format)'
Debug.Print Format(inputDate, "dd/mm/yyyy")
'It`s magic! The above line will print 6/1/2009'
'which is the correct format for my Regional Settings'
End Sub
It might seem like magic, but it isn't. It takes advantage of how the Format
function works in conjunction with the current regional settings.
For example, suppose your Regional Settings are configured to use the "mm/dd/yyyy"
format for dates.
Now, you get a date string from a user in "dd/mm/yyyy"
format. If you Format
this date string and tell Format
to also use "dd/mm/yyy"
, it will swap the month and day parts of the date because your settings say dates are in "mm/dd/yyyy"
format.
In other words, Format
always assumes the date string from the user is formatted according to your current Regional Settings (in this case, "mm/dd/yyyy"
), so when you tell it to format the date using "dd/mm/yyyy"
, it will force it to swap the month and day parts. If your Regional Settings use the same format as the user-provided date, this code will still work: Format
will simply return the user date unchanged. Confused yet? ;)
The same thing will happen if your Regional Settings are set for "dd/mm/yyyy"
and the user sends a date in "mm/dd/yyyy"
format.
The catch is that you have to know ahead of time which format the user is sending dates in. They can't start mixing and matching date formats (and they shouldn't be anyway).
EDIT (by MarkJ) - just to prove that Mike's code can convert a string to Date. Mike, please roll back or change this edit if you want.
Public Sub Test()
Dim dte As Date
For dte = #1/1/2009# To #12/31/2009#
Call TestDateParsing(dte)
Next dte
End Sub
Public Sub TestDateParsing(ByVal dteIn As Date)
'On my computer, the date format is U.S. (mm/dd/yyyy)'
'This test creates a date string in dd/mm/yyyy format to'
'simulate user input in a different format'
Dim sExpected As String
sExpected = Day(dteIn) & " / " & Month(dteIn) & " / " & Year(dteIn)
Dim inputDate As String
Dim dte As Date
inputDate = Format(dteIn, "dd/mm/yyyy")
dte = Format(inputDate, "dd/mm/yyyy")
Debug.Assert sExpected = Day(dte) & " / " & Month(dte) & " / " & Year(dte)
Debug.Print sExpected
End Sub