I have a file with strings that are in the format YYMMDD. eg. 120216 (will always be in this format).
I want to convert this into a date ideally in the format DDMMYY or DDMMYYYY.
Has anyone come across a similar problem and how did they resolve it?
I have a file with strings that are in the format YYMMDD. eg. 120216 (will always be in this format).
I want to convert this into a date ideally in the format DDMMYY or DDMMYYYY.
Has anyone come across a similar problem and how did they resolve it?
You can split the string and then use DateSerial. See this example.
Option Explicit
Sub Sample()
Dim sDate As String
Dim Y As Long, M As Long, D As Long
sDate = "120216"
Y = Left(sDate, 2)
M = Mid(sDate, 3, 2)
D = Right(sDate, 2)
Debug.Print Format(DateSerial(Y, M, D), "DDMMYY")
Debug.Print Format(DateSerial(Y, M, D), "DDMMYYYY")
End Sub
Followup from comments
Thanks, I am probably going to have to write up a function where I can pass in string dates to get converted. Any chance that the Debug... line be saved into a variable? (can't seem to) or an alternative work around? – Marco Susilo 4 mins ago
I have not done any error handling. I am sure you can take care of that?
Option Explicit
Sub Sample()
Dim Ret As String
Ret = GetDate("120216", "DDMMYY")
Debug.Print Ret
Ret = GetDate("120216", "DDMMYYYY")
Debug.Print Ret
End Sub
Function GetDate(sDate As String, sFormat As String) As String
Dim Y As Long, M As Long, D As Long
Y = Left(sDate, 2)
M = Mid(sDate, 3, 2)
D = Right(sDate, 2)
GetDate = Format(DateSerial(Y, M, D), sFormat)
End Function