charlie
charlie

Reputation: 481

vb.net add/remove days to date and change format

Function GetFirstDayOfMonth(ByVal dtDate As Date) As DateTime
        Dim dtFrom As Date = dtDate
        dtFrom = dtFrom.AddDays(-(dtFrom.Day - 1))
        Return dtFrom
    End Function

i use this function to get the first day of a month and i call it here:

detail_fromdate = GetFirstDayOfMonth(DateTime.Now.ToString("yyyy-MM-dd")).ToString("dd-MM-yyyy)

but its not changing the format to dd-MM-yyyy

Upvotes: 0

Views: 754

Answers (1)

Steve
Steve

Reputation: 216243

Please understand that dates have no format. It is the ToString or other methods that apply a formatting appearance to your date converting it to a string suitable to be displayed.

Your function could be written as

Function GetFirstDayOfMonth(ByVal dtDate As Date) As DateTime
    return new DateTime(dtDate.Year, dtDate.Month, 1)
End Function

and when you get the date back

Dim detail_fromdate As DateTime = GetFirstDayOfMonth(DateTime.Today)
Dim stringAsDateToBeDisplayed = detail_fromdate.ToString("dd-MM-yyyy")

or whatever format you want to display

By the way, your code works just because you have the Option Strict set to Off and this allows to pass a string when the GetFirstDayOfMonth expects a datetime.
Option Strict Off allows this automatic conversion from one type to another but more often this kicks you in unexpected ways if you don't pay a lot of attention to this issue. If it is not to late use Option Strict On.

Upvotes: 2

Related Questions