简体   繁体   中英

How to get last five days in a month with VB.NET

I have a form to do stock opname in inventory. To access this form is by click a button to open the form. I want to validate, that user could open this form in range days five days till end date in a month. For example: User could only access this form in days: date 27 till 31 August. How i can get last five days in a month with vb.net. I have no idea how to write the code. I would appreciate if there is a help. Thanks in advance

The trick is to add five days and see if you're next month (or next year in December).

Try this function:

Private Function IsWithinLastFiveDays(ByVal dt as DateTime) as Boolean
  dim newDate as datetime = dt.AddDays(5)
  if newdate.Month > dt.Month then return true
  if newdate.Year > dt.Year then return true
  return false
End function

Spell, try to take the last day of the month first and then subtract 5 days ... Example:

Public Function CalcDate(ByVal month1 As Byte) As Date

        Try
            Dim dtLastDay As DateTime = Convert.ToDateTime(Date.Now.Year().ToString() & "/" + month1.ToString("00") & "/" + "01")

            dtLastDay = dtLastDay.AddMonths(1)
            dtLastDay = dtLastDay.AddDays(-5)

            'Don't catch Sunday and Saturday
            'If (dtLastDay.DayOfWeek = DayOfWeek.Sunday) Then
            'dtLastDay = dtLastDay.AddDays(-2)
            'ElseIf (dtLastDay.DayOfWeek = DayOfWeek.Saturday) Then
            'dtLastDay = dtLastDay.AddDays(-1)
            'End If

            CalcDate = dtLastDay

        Catch ex As Exception
            MessageBox.Show(ex.Message)
            Return ""
        End Try

    End Function

There are numerous ways that this could be done. Here is just one:

Dim currentDate = Date.Now

If currentDate.Day > Date.DaysInMonth(currentDate.Year, currentDate.Month) - 5 Then
    'We are in the last 5 days of the month.
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM