views:

130

answers:

1

I want to be able to present "today" and "yesterday" for recent dates in my application. I've got a date formatter in use currently to show dates (retrieved from data records) and will keep using this for anything more than a couple of days old. I just really like the way the SMS app in the iPhone shows dates for recent messages and would like to emulate this.

The time-stamps that I have to work with are generated on a server that the phone downloads the data records from. All times are therefore generated at UTC (i.e. GMT) time.

I've been fiddling about with this for a while the solutions I've devised just seem horribly long-winded.

Can anyone suggest how to implement a method that could do this?

Cheers - Steve.

+4  A: 

If this is a web app, you might find PrettyDate useful. I made a vb.net implementation that could easily be converted to another language:

Public Function formatDate(ByVal time As DateTime) As String
    Dim datediff As TimeSpan = Now.Subtract(time)

    Dim days As Integer = datediff.TotalDays

    If days < 1 Then
        Dim seconds As Integer = datediff.TotalSeconds
        Select Case seconds
            Case 0 To 60
                Return "just now"
            Case 61 To 120
                Return "1 minute ago"
            Case 121 To 3600
                Return Math.Floor(seconds / 60) & " minutes ago"
            Case 3601 To 7200
                Return "1 hour ago"
            Case 7201 To 86400
                Return Math.Floor(seconds / 3600) & " hours ago"
        End Select
    ElseIf days < 31 Then
        Select Case days
            Case 1
                Return "yesterday"
            Case 2 To 7
                Return days & " days ago"
            Case Is > 7
                Return Math.Ceiling(days / 7) & " weeks ago"
        End Select
    Else : Return time.ToString("MM/dd/yyyy")
    End If
End Function
dtryan