วันศุกร์ที่ ๒๐ มีนาคม พ.ศ. ๒๕๕๒

ฟังก์ชั่นหาวันแรกและวันสุดท้ายของเดือน (Get first and last day of month)

คำว่าวันสุดท้ายของเดือนในที่นี้ หมายถึงวันใน data type แบบ DateTime (หรือ Date) นะครับ ไม่ใช่หมายถึงเดือนนั้นมีกี่วัน เพราะถ้าหาเดือนนั้นมีกี่วันก็แค่ใช้ Method ชื่อ DaysInMonth (พร้อมระบุปีเดือน) ก็ได้คำตอบแล้ว โค้ดข้างล่างเป็นตัวอย่างแนวทางการหาคำตอบเท่านั้น เพราะที่จริงสามารถพลิกแพลงได้หลายวิธีครับ ลองดูกันเลยครับ

'VB.NET
'หาวันแรกของเดือน จากวันปัจจุบัน
Function GetFirstDayOfMonth(ByVal CurrentDate As DateTime) As DateTime
   Return (New DateTime(CurrentDate.Year, CurrentDate.Month, 1))
End Function
'หาวันแรกของเดือน ที่เป็นวันทำงาน (จันทร์-ศุกร์) จากวันปัจจุบัน
Function GetFirstWorkingDayOfMonth(ByVal CurrentDate As DateTime) As DateTime
   With New DateTime(CurrentDate.Year, CurrentDate.Month, 1)
      If .DayOfWeek = DayOfWeek.Saturday Then
         Return .AddDays(2)
      ElseIf .DayOfWeek = DayOfWeek.Sunday Then
         Return .AddDays(1)
      Else
         Return .AddDays(0)
      End If
   End With
End Function
'หาวันสุดท้ายของเดือน จากวันปัจจุบัน
Function GetLastDayOfMonth(ByVal CurrentDate As DateTime) As DateTime
   With CurrentDate
      Return (New DateTime(.Year, .Month, Date.DaysInMonth(.Year, .Month)))
   End With
End Function
แหล่งข้อมูล :
first day of month - eggheadcafe
First and Last Day Of Month - vbforums

Related Post