日期/时间Swift中的自然语言近似 [英] Date/Time Natural Language Approximation in Swift

查看:130
本文介绍了日期/时间Swift中的自然语言近似的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Swift将UTC格式的日期从API转换为人类可读的近似格式。



我正在寻找类似以下的东西:


2015-07-14T13:51:05.423Z



大约两周前


在Swift中最好的方法是什么?虽然最好这可以直接格式化字符串,我明白这可能需要将字符串转换为NSDate对象。



任何帮助将非常感激。 b
$ b

编辑:我的问题已被标识为可能与另一个问题重复。下面的汤姆的解决方案是为Swift编写的,比创建一个新的方法更优雅。

解决方案

脚步。首先,将日期字符串转换为 NSDate

  let dateString = 2015-07-14T13:51:05.423Z

let df = NSDateFormatter()
df.dateFormat =yyyy-MM-dd'T'HH:mm:ss.SSSZ
let date = df.dateFromString(dateString)



接下来,使用 NSDateComponentsFormatter

code>以获取所需的字符串:

  let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyle .Full
formatter.includesApproximationPhrase = true
formatter.includesTimeRemainingPhrase = false
formatter.allowedUnits = NSCalendarUnit.WeekOfMonthCalendarUnit

如果let pastDate = date {
let dateRelativeString = formatter.stringFromDate(pastDate,toDate:NSDate())
}

7月28日,因此该字符串的结果是约2周。 allowedUnits 属性是一个位字段,因此您可以指定允许的单位类型数量。


I am attempting to convert a UTC formatted date from an API to a human-readable approximation format using Swift.

I'm looking for something like the following:

2015-07-14T13:51:05.423Z

to

About two weeks ago

What is the best approach to this in Swift? While optimally this could format strings directly, I understand that this will probably require casting the string to a NSDate object.

Any help would be greatly appreciated.

EDIT: My question had been identified as a possible duplicate of another question. Tom's solution below is written for Swift and much more elegant than creating a new method in regards to my situation.

解决方案

You need two steps. First, convert your date string to an NSDate:

let dateString = "2015-07-14T13:51:05.423Z"

let df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = df.dateFromString(dateString)

(If that's not an exact representation of the strings you get, you'll have to change the date format string to get this to convert).

Next, use NSDateComponentsFormatter to get your desired string:

let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyle.Full
formatter.includesApproximationPhrase = true
formatter.includesTimeRemainingPhrase = false
formatter.allowedUnits = NSCalendarUnit.WeekOfMonthCalendarUnit

if let pastDate = date {
    let dateRelativeString = formatter.stringFromDate(pastDate, toDate: NSDate())
}

Today is July 28, so the result for that string is "About 2 weeks". The allowedUnits attribute is a bit field, so you can specify as many unit types as you want to allow.

这篇关于日期/时间Swift中的自然语言近似的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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