Swift

Swiftで現在からの経過時間を計算するNSDateのExtension

More than 3 years have passed since last update.

Swiftでつかえる、TwitterやFacebookのような現在からの経過時間を計算するライブラリをExtensionで作りました。「1sec,2minutes,3hours,4days」と表示するアレです。


ソース


TimeInterval+NSDate.swift

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
}
}



使い方


その1


TimeInterval+NSDate.swift

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"
}


その2


TimeInterval+NSDate.swift

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")


その3


TimeInterval+NSDate.swift

var c = "2015-02-06 19:48:31".toDate(format: "yyyy-M-d HH:mm:ss")?.stringForTimeIntervalSinceCreated() // optional

println(c) // Optional("5 days")

引用 http://hayatomo.com/2015/02/09/1504