Get difference days from today - faster way?

jmon

Well-Known Member
Licensed User
Longtime User
Hello,

I am trying to get the difference amount of days from today. Is there a faster way to do it, because I find my method quite slow.

The result I want to get is for example 1 (day) if the date was yesterday, 2 for the day before yesterday. I want the difference in days, starting at midnight, not a 24h difference.

This code works as expected, but I feel it is a bit slow when processing many dates:

B4X:
Sub GetDayDifferenceFromToday(Ticks As Long) As Int
    Dim OldFormat As String
    OldFormat = DateTime.DateFormat
   
    Dim fromDate, toDate As Long
    Dim fromYear, fromMonth, fromDay, toYear, toMonth, toDay As Int
   
    DateTime.DateFormat = "yyyy"
    fromYear = DateTime.Date(DateTime.Now)
    toYear = DateTime.Date(Ticks)
   
    DateTime.DateFormat = "MM"
    fromMonth = DateTime.Date(DateTime.Now)
    toMonth = DateTime.Date(Ticks)
   
    DateTime.DateFormat = "dd"
    fromDay = DateTime.Date(DateTime.Now)
    toDay = DateTime.Date(Ticks)
   
    fromDate = DateUtils.SetDate(fromYear, fromMonth, fromDay)
    toDate = DateUtils.SetDate(toYear, toMonth, toDay)
   
    Dim Diff As Int
    Diff = ((fromDate - toDate) / DateTime.TicksPerDay)

    DateTime.DateFormat = OldFormat
   
    Return Diff
End Sub

What bothers me with this code, is that it seems that there is no other way to get the year, day, month apart from using DateTime.DateFormat.

Thanks
 

jmon

Well-Known Member
Licensed User
Longtime User
B4X:
Dim p As Period = DateUtils.PeriodBetweenInDays(DateTime.Now, Ticks)
Log(p.Days)
Thanks a lot, I read about this in the dateUtils examples, but I didn't this of declaring the p as period.
 
Upvote 0

jmon

Well-Known Member
Licensed User
Longtime User
I did some tests, and it seems that it doesn't work. With your example Erel, it gives a time difference of 0 when the difference hour is less than 24h.
For example, if I want to know the difference day between 2013/07/19 20:00:00 And 2013/07/18 21:00:00, it will return 0, because it's less than 24 hour difference. What I was needing, is that it returns 1, because it's another day (18)
 
Upvote 0

jmon

Well-Known Member
Licensed User
Longtime User
Upvote 0
Top