Good day everyone!
I have a problem about custom date format in VB.NET and I already tried to use these codes:
but none of them are working for me.
First, this the source code where I get the first and last day of the month
Code:
Public Function FirstDayOfMonth(ByVal sourceDate As DateTime) As DateTime
Return New DateTime(sourceDate.Year, sourceDate.Month, 1)
End Function
Public Function LastDayOfMonth(ByVal sourceDate As DateTime) As DateTime
Dim lastDay As DateTime = New DateTime(sourceDate.Year, sourceDate.Month, 1)
Return lastDay.AddMonths(1).AddDays(-1)
End Function
This is the output
3/1/2018 & 3/31/2018
Example:
My first attempt based on Source# 1
Dim startDayMonth As String
Dim endDayMonth As String
startDayMonth = startDayMonth.ToString("dd")
endDayMonth = endDayMonth.ToString("dd")
MsgBox(startDayMonth & " " & endDayMonth)
OUTPUT:
An unhandled exception of type 'System.InvalidCastException' occurred in TIMELOG.exe
Additional information: Unable to cast object of type 'System.String' to type 'System.IFormatProvider'.
My second attempt based on Source# 2
Dim startDayMonth As DateTime
Dim endDayMonth As DateTime
Dim dateFormat As String
dateFormat = "%d"
startDayMonth = FirstDayOfMonth(Now)
endDayMonth = LastDayOfMonth(Now)
startDayMonth = startDayMonth.ToString(dateFormat)
endDayMonth = endDayMonth.ToString(dateFormat)
OUTPUT:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "1" to type 'Date' is not valid.
Own Method #1
Dim startDayMonth As DateTime
Dim endDayMonth As DateTime
Dim dateFormat As String
dateFormat = "yyyy-MM-dd"
startDayMonth = Convert.ToString(FirstDayOfMonth(Now))
endDayMonth = Convert.ToString(LastDayOfMonth(Now))
startDayMonth = startDayMonth.ToString(dateFormat)
endDayMonth = endDayMonth.ToString(dateFormat)
OUTPUT
3/1/2018 3/31/2018
Own Method #2
Dim startDayMonth As DateTime
Dim endDayMonth As DateTime
Dim dateFormat As String
dateFormat = "%yyyy-MM-dd"
startDayMonth = Convert.ToString(FirstDayOfMonth(Now))
endDayMonth = Convert.ToString(LastDayOfMonth(Now))
startDayMonth = startDayMonth.ToString(dateFormat)
endDayMonth = endDayMonth.ToString(dateFormat)
OUTPUT
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "182018-03-01" to type 'Date' is not valid.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…