Android Question Add Months To Date

RishiKumar2210

Active Member
I need to add exact 3 months to date. How to do it? For example I have 01-04-2023, and I need to add 3 months to this date to get 31-06-2023.

Thanks in Advance
 

Mahares

Expert
Licensed User
Longtime User
I need to add exact 3 months to date
Give him a break @emexes . He only started on the forum 31-04-2023. We are joking with you Rishi of course. Back to serious. Here are 3 ways you can obtain the result:
B4X:
DateTime.DateFormat ="dd-MM-yyyy"
    Log("Next date: " & DateTime.Date(DateTime.Add(DateTime.DateParse("01-04-2023"), 0,3,0)))  'Next date: 01-07-2023
    
    Dim p As Period
    p.Months = 3
    Dim nextdate As Long = DateUtils.AddPeriod(DateTime.DateParse("01-04-2023"), p)
    Log("Next date: " & DateTime.Date(nextdate))   'Next date: 01-07-2023
    
    Dim p As Period
    p.Months = 3
    Dim nextdate As Long = DateUtils.AddPeriod(DateTime.DateParse("01-04-2023"), p)
    Log($"Next date: $Date{nextdate}"$)   ' Next date: 01-07-2023
 
Upvote 0

Peter Meares

Member
Licensed User
Longtime User
I would use the DateTime.Add method.
The code below could be shortened (see below) but I added all the steps in.

B4X:
DateTime.DateFormat = "dd/MM/yyyy"
Dim strDate As String = "01/06/2023"
Log(strDate)
Dim lngDate As Long = DateTime.DateParse(strDate)
Dim lngLaterDate As Long = DateTime.Add(lngDate,0,3,0)
Dim strLaterDate As String = DateTime.Date(lngLaterDate)
Log(strLaterDate)

Shorter version
B4X:
DateTime.DateFormat = "dd/MM/yyyy"
Log(DateTime.Date(DateTime.Add(DateTime.DateParse("01/04/2023"),0,3,0)))
 
Upvote 0

BlueVision

Active Member
Licensed User
Longtime User
I would strongly recommend that you first define the format of date and time in your application and then use the built-in tick-based time functions (as seen in the code snippets by Peter Meares and Mahares).
Everything else is a matter of definition, as you would like it to be in your programme. In banking, a month has a length of 30 days. Half of all months deviate from this. So it might be a good idea to first change the months using dateparse, check where you end up and then change the days based on that to suit your needs.
You can also add 90*24*60*60*1000 to the current tick value (milliseconds) datetime.(datetime.now) if the start time is at the moment. That should be exactly 90 days. Due to the different lengths of the months, however, it is quite possible that you will end up in the fourth following month.

It's all a question of definition...
 
Upvote 0
Top