Android Question Convert Date and Time from String to valid DateTime

DataProtec

Member
Licensed User
Android B4A
i need to compare 2 Times, one is storeed in DB, the second is Time Now, i need the differece in "hh:mm"
I have a DateTime Field in my MSSQL DB in format "2020-02-20 09:10:00" I can read this without any problems from DB to String.
But how can i convert this to compare the Time with Now. I tried what i found in the Threads but without exit
I tried the following Code which comes close to my problema.

B4X:
 Dim oldDateformat As String = DateTime.DateFormat
   DateTime.DateFormat = "dd/MM/yyyy"
   Dim sDate As String = "25/12/2014" 'String Date
   Dim lngDate As Long = DateTime.DateParse(sDate) 'Convert String to Long with Date Parse
   DateTime.DateFormat = "dd MMM yyyy" 'Format Date
   Log("Tag: " & DateTime.Date(lngDate))
   DateTime.DateFormat = oldDateformat

Here is my Code, it chrash in line where is "Dim lCheckIn As Long = DateTime.DateParse(sCheckIn)"

B4X:
Dim oldDateformat As String = DateTime.DateFormat
DateTime.DateFormat = "dd/MM/yyyy HH:mm"
Log("sCheckin 2 " & sCheckIn)
    
    sCheckIn = Crsr.GetString2(2) '** Get correct from MSSQL DB as "2020-02-20 09:10:00"
    Dim lCheckIn As Long = DateTime.DateParse(sCheckIn)
    DateTime.DateFormat = "dd MMM yyyy HH mm"
    
    Log("Tag: " & DateTime.Date(lCheckIn))
        
    Log("1 " & DateTime.time(StartTime))
    Log("2 " & DateTime.time(lCheckIn))
        
    DateTime.DateFormat = oldDateformat  'Last but not least; set DateFormat back to it´s old Value!

Anyone can give me help please, thanks
 

DataProtec

Member
Licensed User
Thanks Lucas, working was stupid from my side, did not see the "yyyy-mm-dd hh:mm:ss" with the dash instead the Slash
But how can i get the difference, in Dot Net i have TimeSpan so i can
Dim tDiff as TimeSpan = (lCheckIn - Now) and i get the Difference in HH:mm:ss
 
Upvote 0

DataProtec

Member
Licensed User
Finally i got it, if somebody have the same problema, here what i did, for me Works fine
B4X:
Dim oldDateformat As String = DateTime.DateFormat
    DateTime.DateFormat = "yyyy-mm-dd hh:mm:ss"
    Log("sCheckin 2 " & sCheckIn)
    
    sCheckIn = Crsr.GetString2(2) '** Get correct from MSSQL DB as "2020-03-02 06:20:00"
    
    Dim lCheckIn As Long = DateTime.DateParse(sCheckIn)
    DateTime.DateFormat = "dd MMM yyyy HH mm"
    
    Log("Tag: " & DateTime.Date(lCheckIn))
        
    Log("1 " & DateTime.time(StartTime))
    Log("2 " & DateTime.time(lCheckIn))
        
    DateTime.DateFormat = oldDateformat  'Last but not least; set DateFormat back to it´s old Value!
        
    Dim timeToDate As Period = DateUtils.PeriodBetween(lCheckIn, DateTime.Now)
    Log("Diff " & timeToDate.Hours & ":" & timeToDate.Minutes)

This gives me in Diff = 2:50 (the correct time between the Time stored in DB and Now (is "2020-03-02 09:10:00")
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Upvote 0
Top