Android Question Compare date in a range

Brian Michael

Active Member
Licensed User
Longtime User
Hi,

I have troubles with my code...

I have this code:

B4X:
Dim Filter_Date1 as Long = 0
Dim Filter_Date2 as Long = 0

Sub Activity_Create(FirstTime As Boolean)

'TIME AND DATE
    Dim Now As Long = (DateTime.GetDayOfWeek(DateTime.Now)-3)
    Filter_Date2 = DateTime.Now
    Filter_Date1 = DateTime.Now-(DateTime.TicksPerDay*Now)
    
End Sub


Public Sub DayInFilter(Day As String) As Boolean
    Dim d1 As String = DateTime.Date(Filter_Date1)
    Dim d2 As String = DateTime.date(Filter_Date2)
   
Dim Result as Boolean = DB.CompareDates(Day, d1,d2))

    Log("Date: " & Day & " between dates Start: " & d1 &" End: " & d2 & " is " & Result

    Return Result
End Sub

Public Sub CompareDates(CurrentDate As String, Date1 As String, Date2 As String) As Boolean
    DateTime.DateFormat = "dd/mm/yyyy"

    Dim cd As Long = DateTime.DateParse(CurrentDate)
    Dim d1 As Long = DateTime.DateParse(Date1)
    Dim d2 As Long = DateTime.DateParse(Date2)
   
    If cd >= d1 And cd <=d2 Then
        Return True
       
    Else
        Return False
    End If
End Sub


And i get logs:
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
Fecha: 2/12/2020 between dates Start: 01/45/2020 End: 05/45/2020 is true
Fecha: 2/12/2020 between dates Start: 01/45/2020 End: 05/45/2020 is true
Fecha: 2/12/2020 between dates Start: 01/45/2020 End: 05/45/2020 is true

As you can see Filter_Date1 and Filter_Date2 have a wrong Month and another error is the result its says true.

For Default the Filters may have the first day of the month and the current day.
 
Thsnks @Erel for answer.

Its works i change the comparison method using the long value for compare the dates.


I change:
DateTime.DateFormat = "dd/mm/yyyy"

To:
DateTime.DateFormat = "dd/MM/yyyy"
 
Upvote 0
Its works i change the comparison method using the long value for compare the dates.
Here is my way of doing it taking advantage of DateUtils.PeriodBetweenInDays unl;ess of course Erel finds a flaw with it:
Code:
Sub IsDateBetween(Dstart As String, Dend As String, MyDate As String) As Boolean
    DateTime.DateFormat="dd/MM/yyyy"
    Dim p1 As Period=DateUtils.PeriodBetweenInDays(DateTime.DateParse(Dstart), DateTime.DateParse(MyDate))
    Dim p2 As Period=DateUtils.PeriodBetweenInDays(DateTime.DateParse(MyDate), DateTime.DateParse(Dend))
    Return (p2.Days>= 0 And p1.Days >= 0)
End Sub

to test it:
Code:
Log (IsDateBetween("30/11/2020",  "1/12/2020", "27/11/2020"))  'false
Log (IsDateBetween("30/11/2020",  "2/12/2020", "2/12/2020"))  'true
Log (IsDateBetween("30/11/2020",  "2/12/2020", "1/12/2020"))  'true
Log (IsDateBetween("30/11/2020",  "2/12/2020", "30/11/2020"))  'true
 
Upvote 0
Back
Top