Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active August 23, 2016 19:57
Show Gist options
  • Save KentarouKanno/82138f4d76554030a5f3 to your computer and use it in GitHub Desktop.
Save KentarouKanno/82138f4d76554030a5f3 to your computer and use it in GitHub Desktop.
NSCalendar

NSCalendar

★ 入力年月日の前日を取得する

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
let inputDate = dateFormatter.dateFromString("2015/3/01")

// 入力年月日の前日 
let inputDateBeforeDay = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -1, toDate: inputDate!, options: NSCalendarOptions.init(rawValue: 0))

★ 2つの時間から差を出力する
参考URL: teratail_41673 サンプル

let startDate = NSDate()
let endDate   = NSDate(timeIntervalSinceNow: (60 * 60 * 24 * 400))

// 60 * 60 * 24 * 400 => 1年1月4日
// 60 * 60 * 24 * 50  => 50日前
// 60 * 60            => 1時間前
// 60                 => 1分前
// 59                 => 59秒前


let cal = NSCalendar.currentCalendar()

let unitFlags1: NSCalendarUnit = [.Year, .Month, .Day, .Hour, .Minute, .Second]
let unitFlags2: NSCalendarUnit = [.Day]
let components1 = cal.components(unitFlags1, fromDate: startDate, toDate: endDate, options: NSCalendarOptions())
let components2 = cal.components(unitFlags2, fromDate: startDate, toDate: endDate, options: NSCalendarOptions())

var result = ""
if components1.year > 0 {
    result = String(components1.year) + "" + String(components1.month) + "" + String(components1.day) + ""
} else if components1.month > 0  || components1.day > 0 {
    result = String(components2.day) + "日前"
} else if components1.hour > 0 {
    result = String(components1.hour) + "時間前"
} else if components1.minute > 0 {
    result = String(components1.minute) + "分前"
} else {
    result = String(components1.second) + "秒前"
}

result
//=> 結果出力
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment