从 Unix 时间戳获取人类可读的相对时间和日期?
从像 1290529723 这样的 unix 时间戳开始,我(假设 gmt)如何获取以下信息:
今天(如果是,则是什么时间)
in过去 7 天(如果是的话,哪一天......星期一, 周二等?)
- 超过一周(如果是这样,如何以 dd/mm/yy 输出 格式?)
我需要这个消息列表,例如 iPhone 的邮件应用程序,其中显示相对于当前日期和时间的日期/时间,如下所示
15:45
Yesterday
Sunday
Saturday
10/10/10
等
:
Starting with a unix timestamp like 1290529723, how would I (assuming gmt) get the information on whether it is:
today (if so, what time)
in the last seven days (if so, which day ... mon,
tues etc?)- older than a week (if so, how to output in dd/mm/yy
format?)
I need this for a list of messages like the iPhone's Mail app, where date/times are shown relative to the current date and time, like so:
15:45
Yesterday
Sunday
Saturday
10/10/10
etc
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
需要进行一些调整才能获得尊重设备区域设置的解决方案。以下方法relativeStringFromDate 返回一个表示日期的字符串,格式如下:
仅日期部分,如果根据区域设置,日期已超过一周前(例如,美国为“1/20/2012”,欧洲为“20/1/2012”)
如您所述和 Brad 的答案,您可以使用 NSDate 的 dateWithTimeIntervalSince1970 从时间戳获取 NSDate。
It takes a bit of fiddling to get a solution that respects the device's locale. The following method relativeStringFromDate returns a string representing the date, formatted as following:
just the date component if the date is over one week ago, according to locale (e.g. '1/20/2012' in US vs '20/1/2012' in Europe)
As mentioned in yours and Brad's answers, you can obtain an NSDate from a timestamp using NSDate's dateWithTimeIntervalSince1970.
我使用这个方法将 unix 时间戳更改为可读的相对字符串。可能在新年的头几天无法正常工作,但希望你宿醉得太厉害而不会注意到。
I made this method to change the unix time stamp into a nice readable, relative string. Probably doesn't work properly in the first few days of a new year, but hopefully you should be too hungover to notice.
我个人喜欢 github 上的 https://github.com/kevinlawler/NSDate-TimeAgo 库。它只有两个文件,使用起来非常简单。如果您愿意的话,它还具有本地化功能!
I personally like the https://github.com/kevinlawler/NSDate-TimeAgo library on github. It only has two files and it's very simple to use. It also has localization if you want!
NSDateFormatter 类有你需要的。它确实通过 doesRelativeDateFormatting 方法执行“今天”、“明天”等操作。
希望这可以帮助那些来到这里并且不想使用外部类或创建自己的类的人。
The NSDateFormatter class has what you need. It does do "today", "tomorrow" etc. via the doesRelativeDateFormatting method.
Hope that helps someone else who lands on here and doesn't want to use an external class or creates his own.
有一个库:
TTTTimeIntervalFormatter
在 mattt 的FormatterKit< /代码>:)
There is a library for that:
TTTTimeIntervalFormatter
in mattt'sFormatterKit
:)将其转换为 NSDate:
然后与其他日期进行比较:
Convert it to an NSDate with:
Then compare to other dates with: