如何将时间戳转换为用户友好的时间字符串 [英] How can I convert a timestamp to a user-friendly time string

查看:129
本文介绍了如何将时间戳转换为用户友好的时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在我的申请中提出今天和昨天的最近日期。我有一个日期格式化程序正在使用当前显示日期(从数据记录检索),并将继续使用这个超过几天的任何东西。我只是喜欢iPhone中的短信应用程序显示最近消息的日期,并希望模拟这个。



我必须使用的时间戳在手机下载数据记录的服务器上生成。因此,所有时间都以UTC(即GMT)时间生成。



我一直在讨厌这一段时间,我设计的解决方案看起来似乎很长时间。


$ b $任何人都可以建议如何实现可以做到这一点的方法?



干杯 - Steve。

解决方案

如果这是一个网络应用程序,您可能会发现 PrettyDate 有用。我做了一个vb.net实现,可以轻松地转换成另一种语言:

 公共函数formatDate(ByVal time As DateTime)As String 
Dim datediff As TimeSpan = Now.Subtract(time)

Dim days As Integer = datediff.TotalDays

如果days< 1然后
Dim seconds As Integer = datediff.TotalSeconds
选择案例秒
案例0到60
返回刚刚
案例61到120
返回1分钟前
案例121 To 3600
返回Math.Floor(秒/ 60)& 分钟前
案例3601至7200
返回1小时前
案例7201至86400
返回Math.Floor(秒/ 3600)& 小时前
结束选择
ElseIf days< 31然后
选择案例天
案例1
返回昨天
案例2到7
返回日期& 天前
案例是> 7
返回Math.Ceiling(days / 7)& 周前
结束选择
否则:返回time.ToString(MM / dd / yyyy)
如果
结束函数


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.

解决方案

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

这篇关于如何将时间戳转换为用户友好的时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆