In
VbClassic...
Is it possible to convert a string to a Date, in a way that does >NOT< depend on the current locale settings?
Debug.Assert Format$(CDate("01/02/2001"), "MM/DD/YYYY") = "01/02/2001"
...works when short date format is 'M/d/yy', but fails when it's 'd/M/yy'.
(In other words, I want a "CDate-like" function that always converts "01/02/2001" to January 2nd, regardless of locale; never February 1st.)
--
JeffGrigg
But that behaviour would be broken: to me, in EN-gb, 9/11 is the 9th of November. Use IsoDateFormat or (long or short) month names to avoid ambiguity. Question, though: in non-EN locales, can you still use EN month names, or would I, in DE say, use Januar, Februar etc? -- JonKale
If you parse the string yourself, you can use the D
ateAdd() function to add the month and day separately to "01/01/YYYY". --
WayneMack
Or you can use the dateserial Function to assemble the date after splitting the string yourself -- AndyMorris
CDate("#12/31/2000#")
was suggested.
Doesn't work.
--
JeffGrigg
Try it without the quotes. As I recall, #s are the delimiters for dates, while "s are for strings -- as shown above, you are making a string that starts and ends with the symbol "#". --
JimRussell
Right, I really do have a string:
Suppose I have...
Private Function MyCDate(ByVal pstr As String) As Date
MyCDate = CDate(pstr)
End Function
When I do "Control Panel -> Regional Settings -> Date (tab)" and set "Short date style" to
"M/d/yy", MyCDate("01/02/2000") returns January 2nd, as it should.
Now I set "Short date style" to
"d/M/yy",
the same MyCDate("01/02/2000") call returns
February 1st.
This is not good; I need to get the same result from the same input and VB code, regardless of the locale (regional settings).
--
JeffGrigg
It's working the way it's supposed to isn't it?
Not meaning to be rude but as already suggested, split the string up and use D
ateSerial(y,m,d) if the format is fixed.
Or switch to the
IsoDateFormat --
SamJessup
DateSerial is the answer!!!
IsoDateFormat seems to work, but there's no documentation that says that CDate() will accept ISO date format in addition to your locale-defined date format.
(...at least none that I can find. ;-)
I must admit, I pretty much detest regional date formats. And not being american, I fail to see why the date is anything other than dd/mm/yyyy. (I'm sure there is a reason, but can't figure out why...)
Anyhow, what I use is this...
dtmDate = CDate("12 January 2002")
if you only have the month as a number, I guess it would be something more like this...
dtmDate = CDate("12 " & MonthName(lngMonthValue, false) & " 2002")
Excuse that last bit if it is slightly wrong, as I don't have VB installed anymore to check syntax. (Using C# now)
Perhaps I've missed the point, but I've found this to be a pretty versatile solution
--
DaveBeer
CategoryVbClassic