LoginSignup
7

More than 5 years have passed since last update.

Swiftで超簡単に日付から年齢を算出する方法 (Swift 3.0.1)

Last updated at Posted at 2016-11-10

どうぞ!

DateUtils.swift

import Foundation

class DateUtils {

    static func age(byBirthDate birthDate: Date) -> Int {
        let timezone: NSTimeZone = NSTimeZone.system
        let localDate = NSDate(timeIntervalSinceNow: Double (timezone.secondsFromGMT)) as Date

        let localDateIntVal = Int(string(localDate, format: "yyyyMMdd"))
        let birthDateIntVal = Int(string(birthDate, format: "yyyyMMdd"))

        print(localDateIntVal!)
        print(birthDateIntVal!)

        let age = (localDateIntVal! - birthDateIntVal!) / 10000
        print(age)

        return age
    }

    static func date(_ string: String, format: String) -> Date {
        let formatter: DateFormatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.date(from: string)! as Date
    }

    static func string(_ date: Date, format: String) -> String {
        let formatter: DateFormatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: date as Date)
    }

    static func simpleDate(string: String) -> String {
        let tmp = string.replacingOccurrences(of: "-", with: "/")
        let res = tmp.substring(from: tmp.index(tmp.startIndex, offsetBy: 5))
        return res
    }

}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7