Cursussen/Courses Codesnippets     Top 
B4A-calendar - Display the month


1. Date calculations
But as you have noticed the day numbers are not correct yet. The month of May 2022 only has 31 days and not 42 days! So we need to find the number of days in each month.
The first day of each month is not always a Sunday (as it is in May 2022). We need to know at which day the month begins (in April 2022 it was on a Friday).
For all related date calculations we can use the built-in DateTime object and its properties and methods.
We can also use the DateUtils library (link: DateUtils) to do some extra calculations with dates.
Lets add some code to display the month correctly.
Declarations below the daynumber declaration:
Private currentticks As Long = DateTime.Now
Private currentmonth As Int = DateTime.GetMonth(currentticks)
Private currentyear As Int = DateTime.GetYear(currentticks)
Private currentday As Int = DateTime.GetDayOfMonth(currentticks)
Private firstdayticks As Long
Initializations before the month/year label code:
' date initializations
firstdayticks = DateUtils.SetDate(yr,mnth,1)
Private startdaynumber As Int = DateTime.GetDayOfWeek(firstdayticks)	   '1 = sunday, 7 = saturday
Private enddaynumber As Int = DateUtils.NumberOfDaysInMonth(mnth,yr)


2. Date tests
Now we need to test a few things (in the inner loop):
If c < startdaynumber And r = 1 Then
	Private lbl As Label = set_label("")
Else
	If daynumber > enddaynumber Then
		Private lbl As Label = set_label("")
	Else
		If daynumber = currentday And mnth = currentmonth And yr = currentyear Then
			Private lbl As Label = set_label(daynumber)
		Else
			' sunday = 1 - saterday = 7
			If c = 1 Or c = 7 Then
				Private lbl As Label = set_label(daynumber)
			Else
				Private lbl As Label = set_label(daynumber)
			End If
		End If
		daynumber = daynumber + 1
	End If
End If
'Private lbl As Label = set_label(daynumber)
pnl1.AddView(lbl,leftpos+boxwidth*(c-1),toppos+(boxheight*2)+boxheight*(r-1),boxwidth,boxheight)
If the column number is smaller than de start day number and it is the first row then the label should not display a number.
If the day number becomes greater than the last day number of the month then the label should not display a number.
In all other cases the label should display a day number.
The remaining tests are for the background coloring (see next chapter).
Notice that the line to add 1 to the day number is moved to the end of the second else block.
The app now looks like this (for March of 2022):