DateUtils is a code module with a set of useful date and time related methods. It complements DateTime api, it doesn't replace it. The methods included in DateUtils: 'Calculates the period between two date instances. 'This method returns a Period type with years, months, days, hours, minutes...
Sub Thing_results(TTT As Int)
Dim TFrom As Long
Dim TTo As Long
Dim DT As String
DateTime.DateFormat ="yyyy-MM-dd HH:mm:ss"
TTo=DateTime.Now
Select Case TTT
Case 1
TFrom=TTo-(DateTime.TicksPerday/2) '12h
Case 2
TFrom=TTo-(DateTime.TicksPerday) '1 day
Case 3
TFrom=TTo-(DateTime.TicksPerday*7) '1 week
Case 4
TFrom=TTo-(DateTime.TicksPerDay*30) '1 month
Case 5
TFrom=TTo-(DateTime.TicksPerDay*365) '1 year
Case 6
End Select
DT="start="&DateTime.Date(TFrom)&"&end="&DateTime.Date(TTo)
Return DT
End Sub
Sorry but this is the wrong way to do date calculations.
As @Erel says watch the Date & Time Tutorial. You should be using the Period object
the correct code is:
B4X:
Sub Thing_results(TTT As Int) As String
Private per As Period
per.Initialize
Dim TFrom As Long
Dim TTo As Long
Dim DT As String
DateTime.DateFormat ="yyyy-MM-dd HH:mm:ss"
TTo=DateTime.Now
Select Case TTT
Case 1
per.hours = -12
'TFrom=TTo-(DateTime.TicksPerday/2) '12h
Case 2
per.Days = -1
'TFrom=TTo-(DateTime.TicksPerday) '1 day
Case 3
per.Days = -7
'TFrom=TTo-(DateTime.TicksPerday*7) '1 week
Case 4
per.Months = -1
'TFrom=TTo-(DateTime.TicksPerDay*30) '1 month
Case 5
per.Years = -1
'TFrom=TTo-(DateTime.TicksPerDay*365) '1 year
Case 6
End Select
TFrom = DateUtils.AddPeriod(TTo,per)
DT="start="&DateTime.Date(TFrom)&"&end="&DateTime.Date(TTo)
Return DT
End Sub
The reason for this is because of leap years, months having days <> 30 etc. AddPeriod handles all of that for you.
I really don't think the way you did it is the correct way (a month is not always 30 days), but here is a sub that will do what you want and you can add or subtract minutes, days, months, years and mix any combination of period:
B4X:
'Calculate a string date with time after adding or subtracting a period
Sub MyDate(dstart As String, tm As Double, th As Double, td As Double, tmo As Double, ty As Double) As String
DateTime.DateFormat ="yyyy-MM-dd HH:mm:ss"
' Dim dstart As String ="2021-01-03 02:15:24"
Dim p As Period
p.Minutes=tm
p.Hours=th
p.Days=td
p.Months=tmo
p.Years=ty
Return DateTime.Date(DateUtils.AddPeriod(DateTime.DateParse(dstart), p))
End Sub
Whenever you see code with TicksPerDay you know that it is either wrong or at least inaccurate. Don't assume that there are 24 hours per day. You should of course not assume that there are 30 days per month.
I wanted to fill an xchart with data .. The accuracy of time is not necessary.
Finally i use the code of Andrew (Digitwell).
Thank you all for your answers..