B4J Question Format Month with Year

aaronk

Well-Known Member
Licensed User
Longtime User
Hi,

I am trying to work out how to create a list so that is displays the month with the year like:

July 2022
August 2022
September 2022
October 2022
November 2022
December 2023
January 2023
February 2023
March 2023
April 2023
May 2023
June 2023

Then from July 2023 it should be:
July 2023
August 2023
September 2023
October 2023
November 2023
December 2023
January 2024
February 2024
March 2024
April 2024
May 2024
June 2024

I have worked out how to display the months, but can't work out how to do the years..
(most likely not the best way in displaying the months, but seems to work)

B4X:
Dim month_names As List
month_names.Initialize
month_names = DateUtils.GetMonthsNames
        
For i = 6 To 11
   Log(month_names.get(i))
Next
    
For i = 0 To 5
   Log(month_names.get(i))
Next

Any ideas on how to add the year to the month ?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
month_names.Initialize
month_names = DateUtils.GetMonthsNames
Code smell: https://www.b4x.com/android/forum/t...ommon-mistakes-and-other-tips.116651/#content

B4X:
Sub AppStart (Args() As String)
    Dim dates As List = MonthsAndYears(2, 2022, 5, 2024) 'march 2022 -> june 2024
    Log(dates)
End Sub

Private Sub MonthsAndYears(StartMonth0Based As Int, StartYear As Int, EndMonth0Based As Int, EndYear As Int) As List
    Dim res As List
    res.Initialize
    Dim month As Int = StartMonth0Based
    Dim year As Int = StartYear
    Dim months As List =DateUtils.GetMonthsNames
    Do While True
        res.Add(months.Get(month) & " " & year)
        If year > EndYear Or (year = EndYear And month >= EndMonth0Based) Then
            Exit
        End If
        month = month + 1
        If month >= 12 Then
            month = 0
            year = year + 1
        End If
    Loop
    Return res
End Sub
 
Upvote 0

emexes

Expert
Licensed User
Then from July 2023 it should be:
July 2023
...
June 2024

Any ideas on how to add the year to the month ?

In descending order of clarity (or ascending order of conciseness, depending on your outlook) :

B4X:
Dim month_names As List = DateUtils.GetMonthsNames

Dim FirstMonth As Int = 2023 * 12 + 6
Dim LastMonth As Int = FirstMonth + 11    '12 months including FirstMonth

For M = FirstMonth To LastMonth    'or FirstMonth To FirstMonth + 11
    Log(month_names.Get(M Mod 12) & " " & Floor(M / 12))
Next

B4X:
Dim month_names As List = DateUtils.GetMonthsNames

For M = 2023 * 12 + 6 To 2024 * 12 + 5    'or 2023 * 12 + 6 to 2023 * 12 + 6 + 11
    Log(month_names.Get(M Mod 12) & " " & Floor(M / 12))
Next

B4X:
For M = 2023 * 12 + 6 To 2023 * 12 + 17
    Log(DateUtils.GetMonthsNames.Get(M Mod 12) & " " & Floor(M / 12))
Next
 
Upvote 0
Top