I’m trying to format the following value 01/08/2020
Dim value1 as string = '01/08/2020' Response.Write(Format(CDate(value1),"yyyy-MMM-dd"))
The result returned as 2020-Jan-08 instead of 2020-Aug-01
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
There is an easier method for formatting dates. Try this:
Response.Write(DateTime.ParseExact(value1, "dd/MM/yyyy", null).ToString("yyyy-MMM-dd"))
See https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings for the various possible date formats.
Method 2
Out of caution I’d do this
Dim value1 As String = "1/8/2020" '
Dim d As Date
'https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=netcore-3.1#System_DateTime_TryParseExact_System_String_System_String___System_IFormatProvider_System_Globalization_DateTimeStyles_System_DateTime__
If DateTime.TryParseExact(value1, "d/M/yyyy", Nothing, Globalization.DateTimeStyles.None, d) Then
Dim s As String = d.ToString("yyyy-MMM-dd")
Response.Write(s)
Else
Stop 'error placeholder
End If
You’ll need to add code where the Stop is in case of error in the parse.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0