Convert String to Date

yeheya

Board Regular
Joined
May 20, 2004
Messages
162
Could you pls tell me how to convert a string to date in VBA?

strDate="051228" - Input (YYMMDD)

2005-12-28 - Output

I need this in VBA only

Regards,
Yeheya
 

Excel Facts

Which Excel functions can ignore hidden rows?
The SUBTOTAL and AGGREGATE functions ignore hidden rows. AGGREGATE can also exclude error cells and more.
One way:

Code:
Sub Test()
    strdate = "051228"
    MsgBox DateSerial(Left(strdate, 2), Mid(strdate, 3, 2), Right(strdate, 2))
End Sub
 
Upvote 0
Need to bear in mind that a date is basically a number that can be formatted various ways. So if we want it into a cell as a date we use the serial number.
Code:
Sub test()
    Dim strDate As String
    Dim MyDate As Date
    '---------------------------
    strDate = "051228"
    MyDate = DateSerial(2000 + CInt(Left(strDate, 2)), _
        CInt(Mid(strDate, 3, 2)), CInt(Right(strDate, 2)))
    Range("A1").Value = MyDate
    MsgBox (Format(MyDate, "yyyy-mm-dd"))
End Sub
 
Upvote 0
BrianB:
You don't need to convert the parts to integer to use the values in the DateSerial function.
Also that assumes that it will always be a year in 2000+

The way Andrew has it posted it will use Excel's method of figuring out the century.
 
Upvote 0
Code:
You don't need to convert the parts to integer

Experience in answering queries in this forum shows that it is best not to assume exactly how the code is going to be used. It can save further queries.
 
Upvote 0
Code:
x = DateValue("Nov-28-05")
MsgBox x
 
Upvote 0

Forum statistics

Threads
1,214,520
Messages
6,120,013
Members
448,935
Latest member
ijat

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top