J-J
J-J

Reputation: 1113

How to determine if a date is the last day of the month?

Can somebody help me on how to determine if the given date was the last date or day in a month?

For example I have two dates, the one is 2013-01-27 and the other one is 2013-02-28. I need to determine if which date was the last day. So the one that must be display was the 2013-02-28 because its the last day of the month in february while 2013-01-27 was not the last day of the month in January.

What will be the condition that I can use?

Thanks in advance.

Upvotes: 3

Views: 10882

Answers (5)

Vahx
Vahx

Reputation: 636

Hopefully this helps you, its the code for the suggested answer of Shawn de Wet. You can switch Datetime.today.month for another variable with a specific date, then just switch the Today.Adddays(1) with the specific date.AddDays(1)

Dim dateOfToday As DateTime = Today.AddDays(1)

Sub isTodayTheLastDay()
    If DateTime.Today.Month = dateOfToday.Month Then
        'yes its the same month, place code here
    Else
        'no its not the same month, place code here
    End If

End Sub

--

Dim dateToCheck As New DateTime(2013, 4, 21) 'any date you want to check here
Dim Check As DateTime = dateToCheck.AddDays(1)


Sub isTodayTheLastDay()
    If dateToCheck.Month = Check.Month Then
        'yes its the same month, place code here
    Else
        'no its not the same month, place code here
    End If

End Sub

Upvotes: 0

SysDragon
SysDragon

Reputation: 9888

Use this:

Function IsLastDay(ByVal myDate As Date) As Boolean
    return myDate.Day = Date.DaysInMonth(myDate.Year, myDate.Month)
End Function

Upvotes: 6

Enigmativity
Enigmativity

Reputation: 117019

This works for me:

Dim isLastDayOfMonth As Func(Of DateTime, Boolean) = _
    Function (dt) dt.AddDays(1).Day = 1

Upvotes: 2

marcelrf
marcelrf

Reputation: 54

Or you can check if the following day is the first day of the month.

If you are using ruby, you can use the condition:

(date + 1).day == 1

Or if you are using python:

(date + datetime.timedelta(days=1)).day == 1

Cheers!

Upvotes: -1

Shawn de Wet
Shawn de Wet

Reputation: 5976

Add one day and if the resulting answer is not the same month, your date is the last day of the month.

Upvotes: 4

Related Questions