iOS上的NSDate的人性化日期描述 [英] Human friendly date descriptions with NSDate on iOS

查看:152
本文介绍了iOS上的NSDate的人性化日期描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以人性化的方式显示NSDates,例如上周或几天前。类似于 Java的美好时光

I want to display NSDates in a "human-friendly way", such as "last week", or "a few days ago". Something similar to Pretty Time for Java.

什么是最好的办法这,子类NSDateFormatter?

What's the best way to do this, subclassing NSDateFormatter? Before I go and reinvent the wheel, is there already some library for this?

推荐答案

这是Swift 2中的解决方案:

This is the solution in Swift 2:

func formattedHumanReadable(date: NSDate) -> String {
    let formatter = NSDateFormatter()
    formatter.timeStyle = .NoStyle
    formatter.dateStyle = .ShortStyle
    formatter.doesRelativeDateFormatting = true

    let locale = NSLocale.currentLocale()
    formatter.locale = locale

    return formatter.stringFromDate(date)
  }

这篇关于iOS上的NSDate的人性化日期描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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