Android Question DatePeriod to string

trueboss323

Active Member
Licensed User
Longtime User
Hi all,

I am using DateUtlis to try to get the time period between 2 dates. I get the time period already in the ticks format and then I try to convert it into a time string so it displays something like 1 days 12 hours 29 minutes 51 seconds. Here is a code that I am currently using.
B4X:
timeperiodlbl.text = (ConvertTicksToTimeString(ticks))

Sub ConvertTicksToTimeString(t As Long) As String
    Dim  days, hours, minutes, seconds As Int
    days = t / DateTime.TicksPerDay
    hours = t / DateTime.TicksPerHour
    minutes = (t Mod DateTime.TicksPerHour) / DateTime.TicksPerMinute
    seconds = (t Mod DateTime.TicksPerMinute) / DateTime.TicksPerSecond
    Return NumberFormat(days, 2, 0) & "." _
        & NumberFormat(hours, 2, 0) & ":" & NumberFormat(minutes, 2, 0) & ":" & NumberFormat(seconds, 2, 0) & ""
End Sub

So the label text should appear as "1.12:29:51"
but when I get a large time period, something greater than 9 days for example, the hours value go past 24. Here is a example 9.214:18:4
So i suspect it is something to do with the Hours line inside the Sub but I cant figure out how to fix it. Can anyone help please?
 

DonManfred

Expert
Licensed User
Longtime User
B4X:
    Dim p As Period = Dateutils.PeriodBetween(startdate,enddate)
    Log(p)
 
Upvote 0

Mahares

Expert
Licensed User
Longtime User
Here is an example where I use my date format. You can change your date format as fit: Displays:
09.04:22:02

B4X:
Log(ConvertTicksToTimeString("3/24/2015 11:23:15 AM","4/2/2015 3:45:17 PM"))
B4X:
Sub ConvertTicksToTimeString(startdate As String, enddate As String) As String
DateTime.DateFormat="MM/dd/yyyy hh:mm:ss a"  'you can change your date format here
    Dim p As Period = Dateutils.PeriodBetween(DateTime.Dateparse(startdate),DateTime.Dateparse(enddate))
    Return NumberFormat(p.days, 2, 0) & "." _
    & NumberFormat(p.hours, 2, 0) & ":" & NumberFormat(p.minutes, 2, 0) & ":" & NumberFormat(p.seconds, 2, 0)
End Sub
'
 
Upvote 0

trueboss323

Active Member
Licensed User
Longtime User
I did it! I seemed to have fixed the problem now. all I did was change the sub to

B4X:
Sub ConvertTicksToTimeString(t As Long) As String
    Dim  days, hours, minutes, seconds As Int
    days = t / DateTime.TicksPerDay
    hours = (t Mod DateTime.TicksPerDay) / DateTime.TicksPerHour
    minutes = (t Mod DateTime.TicksPerHour) / DateTime.TicksPerMinute
    seconds = (t Mod DateTime.TicksPerMinute) / DateTime.TicksPerSecond
    Return NumberFormat(days, 2, 0) & "." _
        & NumberFormat(hours, 2, 0) & ":" & NumberFormat(minutes, 2, 0) & ":" & NumberFormat(seconds, 2, 0) & ""
End Sub

Now it seems to be working fine.
 
Upvote 0
Top