问题描述
我尝试使用Swift将UTC格式的日期从API转换为人类可读的近似格式。
我正在寻找类似以下的东西:
到
在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
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:
to
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中的自然语言近似的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!