[swift4] NSdateとStringの相互変換関数
NSdateとStringの相互変換関数を記述しておく
class DateUtils { class func dateFromString(string: String, format: String) -> NSDate { let formatter: DateFormatter = DateFormatter() _ = Calendar(identifier: .gregorian) // グレゴリオ歴 formatter.dateFormat = format return formatter.date(from: string)! as NSDate } class func stringFromDate(date: NSDate, format: String) -> String { let formatter: DateFormatter = DateFormatter() _ = Calendar(identifier: .gregorian) // グレゴリオ歴 formatter.dateFormat = format return formatter.string(from: date as Date) } }
使い方
let date = DateUtils.dateFromString(string: "2018-12-25 12:00:00", format: "yyyy-MM-dd HH:mm:ss") let srt = DateUtils.stringFromDate(date, format: "yyyy-MM-dd HH:mm:ss"))