How can I parse a date/time string into an Access Date object given a certain date- and time format?
I can use the CDate() function like this:
Dim StrDateTime As String
Dim DtTest As Date
StrDateTime = "2011-12-31 23:59:59"
DtTest = CDate(StrDateTime)
MsgBox DtTest
This works, Access recognizes the format, fine, but how can I absolutely be sure that this happens under all circumstances (e.g. Date/Time settings Regional Settings, Access version?). I would like to "tell" CDate my special date/time format.
Other option is this (but a lot of code):
Dim StrDateTime As String
Dim IntYear As Integer
Dim IntMonth As Integer
Dim IntDay As Integer
Dim IntHour As Integer
Dim IntMinute As Integer
Dim IntSecond As Integer
StrDateTime = "2011-12-31 23:59:59"
IntYear = Val(Mid(StrDateTime, 1, 4))
IntMonth = Val(Mid(StrDateTime, 6, 2))
IntDay = Val(Mid(StrDateTime, 9, 2))
IntHour = Val(Mid(StrDateTime, 12, 2))
IntMinute = Val(Mid(StrDateTime, 15, 2))
IntSecond = Val(Mid(StrDateTime, 18, 2))
DtTest = DateSerial(IntYear, IntMonth, IntDay)
DtTest = DtTest + TimeSerial(IntHour, IntMinute, IntSecond)
MsgBox DtTest
Other advantage of CDate(): it give a Type Mismatch error on a wrong date/time value. DateSerial + TimeSerial recalculates a new date and time, so "2011-12-31 24:59:59" becomes 01/Jan/2012 0:59:59.
CDate()honours the Regional Settings, regardless of version of Access. One disadvantage ofCDate()is that it does not always give a Type Mismatch when an ambiguous text value does not match Regional Settings e.g. my settings are UK,Month(CDate("28/04/2011"))correctly returns4(April) but the absurd UK valueMonth(CDate("04/28/2011"))also returns 4 when arguably an error would be more useful.CDate("yyyy-mm-dd hh:mm", StrValue)?