-
Get month from date
I'm trying to get the month from a date which is in the US format. So in the date 12/01/99 the month would be 12 (not 1). But I can't work it out. What am I doing wrong? Thank you.
Code:
ElseIf IsDate(txttestdate.Text) = True Then
Dim datval As Date
datval = Format(txttestdate.Text, "mmm d yyyy")
End If
MsgBox "The month is " & Month(datval)
-
Re: Get month from date
Maybe something like this
Code:
Dim datval As Date
If IsDate(txttestdate.Text) Then
datVal = CDate(txttestdate.Text)
MsgBox "The month is " & Month(datval)
End If
-
Re: Get month from date
You are doing a few things wrong (such as using a textbox to input a date, and storing the result of Format to a Date). For more information, see the article Why are my dates not working properly? from our Classic VB FAQs (in the FAQ forum)
Even with MarkT's suggestion you aren't guaranteed the right result ("12/01/99" could still return 1 or 12), which can be corrected by using appropriate control(s) or code (as shown in/via the FAQ article) to ensure that you interpret the date correctly.
-
Re: Get month from date
Yeah sorry, I should explain. The textbox I was using was just for my testing. The US date I want to change is in a csv file.
si_the_geek I actually did read your article, but I got confused, so I thought I'd try out some code and then if necessary ask for some help. So yeah, thanks MarkT for the assistance but as I'm sure you're now aware, CDate is good but, yeah...
"and storing the result of Format to a Date"? I don't understand that. Isn't storing it as a date a good thing? In that other thread I'm pretty sure you said to store the date using literals (#date goes here#) so it can be read correctly. But how do I do that exactly? I'm pretty tired at the moment and it's probably not the best time to be coding. So, thanks once again guys, I'll be back soon.
-
Re: Get month from date
Storing date values as a Date is a good thing, and using date literals (with the value in US format) in your code is good... but the Format function returns a String, and the conversion from String to Date (whether automatic, or via CDate) is where things are not safe.
As the source value is text based, you can use the kind of idea shown in the "How to safely convert a String to a Date" section of the FAQ... but make sure you adapt it to suit the text format you are starting with.
-
Re: Get month from date
If the date is in a string and it is known to be in a valid US format (e.g. mm dd yyyy) the month (number) will be returned from Val(string).
-
Re: Get month from date
I just found out I don't have Split.... You know I think it's time I moved over to VB.Net once and for all. Okay thanks for your input everyone. Who knows, maybe we'll continue the conversation over in the .net forum.