[iOS]Swiftで現在からの経過時間を計算するNSDateのExtension
iOS+Swiftでつかえる、TwitterやFacebookのような現在からの経過時間を計算するライブラリを作りました。「1sec,2minutes,3hours,4days」と表示するアレです。下記のコードをコピペするだけの超絶使い易い形で提供させていただきます。
ソース
TimeInterval+NSDate.swift
[code]
import UIKit
extension NSDate {
func stringForTimeIntervalSinceCreated() -> String {
return stringForTimeIntervalSinceCreated(nowDate:NSDate())
}
func stringForTimeIntervalSinceCreated(#nowDate:NSDate) -> String {
var MinInterval :Int = 0
var HourInterval :Int = 0
var DayInterval :Int = 0
var DayModules :Int = 0
let interval = abs(Int(self.timeIntervalSinceDate(nowDate)))
if (interval >= 86400) {
DayInterval = interval/86400
DayModules = interval%86400
if (DayModules != 0) {
if (DayModules>=3600) {
//HourInterval=DayModules/3600;
return String(DayInterval) + " days"
} else {
if (DayModules >= 60) {
//MinInterval=DayModules/60;
return String(DayInterval) + " days"
} else {
return String(DayInterval) + " days"
}
}
} else {
return String(DayInterval) + " days"
}
} else {
if (interval >= 3600) {
HourInterval = interval/3600
return String(HourInterval) + " hours"
} else if (interval >= 60) {
MinInterval = interval/60
return String(MinInterval) + " minutes"
} else {
return String(interval) + " sec"
}
}
}
}
extension NSDate {
func toString(#format:String, localeIdentifier:String = “ja_JP”) -> String? {
let formatter = NSDateFormatter()
formatter.dateFormat = format
formatter.locale = NSLocale(localeIdentifier: localeIdentifier)
let dateStr = formatter.stringFromDate(self)
return dateStr
}
}
extension String {
func toDate(#format:String, localeIdentifier:String = “ja_JP”) -> NSDate? {
let formatter = NSDateFormatter()
formatter.dateFormat = format
formatter.locale = NSLocale(localeIdentifier: localeIdentifier)
let date = formatter.dateFromString(self)
return date
}
}
[/code]
githubにも置いておきます。
https://github.com/hayakawatomoaki/TimeInterval
使い方1
[code]
if let createdDate = “2015-02-01 14:54:09”.toDate(format: “yyyy-M-d HH:mm:ss”) {
let a = createdDate.stringForTimeIntervalSinceCreated() // non optional
println(a) // “5 days”
}
[/code]
使い方2
[code]
var createdDate = “2015-02-06 14:54:09”.toDate(format: “yyyy-M-d HH:mm:ss”)
var b = createdDate?.stringForTimeIntervalSinceCreated() // optional
println(b) // Optional(“4 hours”)
[/code]
使い方3
[code]
var c = “2015-02-06 19:48:31”.toDate(format: “yyyy-M-d HH:mm:ss”)?.stringForTimeIntervalSinceCreated() // optional
println(c) // Optional(“5 days”)
[/code]
Qiitaにも載せておきます。
http://qiita.com/hayakawatomoaki/items/8f1d5aeb74ba2156245c