簡體   English   中英

查找一個月和一年中VisualBasic的最后一天

[英]Find last day of a month and year VisualBasic

我正在嘗試獲取月份和年份的最后一天,但是我找不到我的代碼在哪里錯誤...

我有這個功能

  Private Function Ultim_dia(mes As String) As String
    Dim ultim As String
    ultim = 1
    Select Case (mes)
        Case 1, 3, 5, 7, 8, 10, 12
            ultim = "31"

        Case 4, 6, 9, 11
            ultim = "30"

        Case 2
            If ((mes) Mod 4) = 0 Then
                ultim = "29"

            Else
                ultim = "28"

            End If
    End Select
    Return ultim
End Function

在我的OnclickButton上,我有這段代碼

 Dim ultim As String
    ultim = tbMes.Text


    Ultim_dia(ultim)
    Select Case (ultim)
        Case "29"
            Me.lb_UltimoDia.Text = "29"
        Case "28"
            Me.lb_UltimoDia.Text = "28"
        Case "30"
            Me.lb_UltimoDia.Text = "30"
        Case "31"
            Me.lb_UltimoDia.Text = "31"
    End Select

我不知道我在哪里錯了,我發現自己在任何地方都不會使用自己的年份...我不知道這是否是問題所在。

我希望你能幫助我,這使我發瘋...

要獲取月份中的天數,請使用內置的DaysInMonth

Dim currentDate As Date = Date.Now
Dim lastDayOfMo = Date.DaysInMonth(currentDate.Year, currentDate.Month)

給定月份和年份(month = 10 and year ='2014')

創建下個月第一天的新日期

Dim q as new date("1", month+1, "2014")

然后做一個負數datedate

dim a as new date = dateadd("d",-1,q)

那應該給您原始月份的最后日期。

經過VBA測試,大概也可以在VB.NET中運行:

Function LastDayOfMonth(theMonth As Long, theYear As Long) As Date
    LastDayOfMonth = DateSerial(theYear, theMonth + 1, 0)
End Function

例如,要獲取2014年10月的最后一天:

Dim d As Date
d = LastDayOfMonth(10, 2014) ' returns 31 Oct 2014

單擊按鈕將調用該函數,該函數將返回傳遞給該函數的年和月中的天數。

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      Dim ultim As String = noOfdays(1989, 8)
 End Sub
 '<-- function
 Public Function noOfdays(ByVal year As Integer, ByVal month As Integer) As String
   Try
        noOfdays = Date.DaysInMonth(year, month)
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
 End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM