Android Code Snippet [B4X] Get time ago from datetime

Convert example 2018/2/2 4:4:23 to 3 minute ago or moment ago

B4X:
Sub GetTimeAgo(Time As String) As String
    
    If IsNumber(Time) = False Then
    
        Dim p(),sDate(),sTime() As String
        p = Regex.Split(" ",Time)
        
        If Time.IndexOf("-") > -1 Then
            sDate = Regex.Split("-",p(0))
            sTime = Regex.Split(":",p(1))
        Else if Time.IndexOf("/") > -1 Then
            sDate = Regex.Split("/",p(0))
            sTime = Regex.Split(":",p(1))
        Else if Time.IndexOf("\") > -1 Then
            sDate = Regex.Split("\",p(0))
            sTime = Regex.Split(":",p(1))
        End If
        
        Time = DateUtils.SetDateAndTime(sDate(0),sDate(1),sDate(2),sTime(0),sTime(1),sTime(2))
        
    End If
    
    Dim diff As Long
    diff = DateTime.Now - Time

    Dim seconds,minutes,days,years,hours As Double
    seconds = Abs(diff) / 1000
    minutes = seconds / 60
    hours = minutes / 60
    days = hours / 24
    years = days / 365

    Dim words As String

    If seconds < 45 Then
        words = "Moment ago"
    Else if seconds < 90 Then
        words = "A minute ago"
    Else if (minutes < 45) Then
        words = Round(minutes) & " minutes ago"
    Else if minutes < 90 Then
        words = "An hour ago"
    Else if hours < 24 Then
        words = Round(hours) & " hours ago"
    Else if hours < 42 Then
        words = "A day ago"
    Else if days < 30 Then
        words = Round(days) & " days ago"
    Else if days < 45 Then
        words = "A month ago"
    Else if days < 365 Then
        words = Round(days / 30) & " month ago"
    Else if years < 1.5 Then
        words = "A year ago"
    Else
        words = Round(years) & " years ago"
    End If

    Return words

End Sub
 
Top