Android Code Snippet [B4X] Calculating the next scheduled time

Name: Find the next scheduled time.

Description by example: You need to start a service each day at 5 am, 6:30 am and 8 pm. You need to find the ticks values of the next scheduled time, either today or tomorrow if it is after 8pm.

B4X:
Dim t As Long = FindNextTime(Array As Double(5, 6.5, 20))
Log($"Next time is: $DateTime{t}"$)

Sub FindNextTime(Times As List) As Long
   Times.Sort(True)
   For Each st As Double In Times
     If SetHours(st) > DateTime.Now Then
       Return SetHours(st)
     End If
   Next
   Return DateTime.Add(SetHours(Times.Get(0)), 0, 0, 1)
End Sub

Sub SetHours(st As Double) As Long
  Dim hours As Int = Floor(st)
  Dim minutes As Int = Round(60 * (st - hours))
  Return DateUtils.SetDateAndTime(DateTime.GetYear(DateTime.Now), _
  DateTime.GetMonth(DateTime.Now), DateTime.GetDayOfMonth(DateTime.Now), hours, minutes, 0)
End Sub
 
Last edited:

ilan

Expert
Licensed User
Longtime User
This is new to me and a very importent thing that anyone should know.

I miss the threads in the theaching forum. There are just to less threads i hope people will add more to it and mention stuff like this :)
 

Traiser

Member
Licensed User
Longtime User
B4X:
Sub controlla_db
    Dim Cursor1 As Cursor
    listaPian.Initialize
    Cursor1 = Sql1.ExecQuery("SELECT * FROM Pianificazione ORDER BY Ora, Minuti ASC")
    For i = 0 To Cursor1.RowCount - 1
        Cursor1.Position = i
        ora = Cursor1.GetInt("ora")
        minuti  = Cursor1.GetInt("minuti")/60
        Log(minuti)
        oraminuti = ora + minuti
        listaPian.Add(oraminuti)
       
    Next
    Log(listaPian.Get(1))
   
    Dim t As Long = FindNextTime(listaPian)
    Log($"Next time is: $Time{t}"$) 
End Sub

Sub FindNextTime(Times As List) As Long
   Times.Sort(True)
   For Each st As Double In Times
     If SetHours(st) > DateTime.Now Then
       Return SetHours(st)
     End If
   Next
   Return DateTime.Add(SetHours(Times.Get(0)), 0, 0, 1)
End Sub

Sub SetHours(st As Double) As Long
   Dim hours As Int = Floor(st)
   Dim minutes As Int = 60 * (st - hours)
   Return DateUtils.SetDateAndTime(DateTime.GetYear(DateTime.Now), _
       DateTime.GetMonth(DateTime.Now), DateTime.GetDayOfMonth(DateTime.Now), hours, minutes, 0)
End Sub

Hi, i use this code for my app. But i have one problem (for this moment only one xD)
i set the time 20.05(HH.mm) but with FindNextTime the start is 20.04.

Log:
Log(minuti) = 0.08333333333333333
Log(listaPian.Get(1)) = 20.083333333333332
Next time is: 20:04:00

the values are not equal(.08333333333333333 and .083333333333332), why?

Thanks!
 
Top