在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
简介:本文将介绍一些关于swift中对于日期的格式化与获取,支持swift4.0 1 extension Date { 2 3 //格式化日期 4 func getDateString() -> String{ 5 let dateFormater = DateFormatter.init() 6 //EEEE:星期几 7 //YYYY:年份 8 //MM:月份 9 //dd:几号 10 //HH:小时 11 //mm:分钟 12 //ss:秒 13 //zzz:时区号 14 15 dateFormater.dateFormat = "EEEE-YYYY-MM-dd HH:mm:ss:zzz" 16 let dateStr = dateFormater.string(from: self) 17 18 return dateStr 19 } 20 21 //获取某个日期为星期几 22 func getDateWeekday() ->String{ 23 let weekdaysTitleArr = ["周日","周一","周二","周三","周四","周五","周六"] 24 let timeInterval:TimeInterval = self.timeIntervalSince1970 25 let days = Int(timeInterval/86400) 26 let weekday = ((days + 4)%7+7)%7 27 return weekdaysTitleArr[weekday] 28 } 29 30 //将日期转换为时间戳(10位) 31 func getTimeStamp() -> Int{ 32 let timeInterval:TimeInterval = self.timeIntervalSince1970 33 let timeStamp = Int(timeInterval) 34 return timeStamp 35 } 36 } 1 class Utility: NSObject { 2 3 //根据时间戳获取时间字符串 4 class func getDateStringFromTimestamp(_ timestamp:Int64) ->String{ 5 let timeInterval:TimeInterval = TimeInterval(timestamp) 6 let date = Date(timeIntervalSince1970: timeInterval) 7 return date.getDateString() 8 } 9 10 //根据时间戳获取日期对象 11 class func getDateFromTimestamp(_ timestamp:Int64) ->Date{ 12 let timeInterval:TimeInterval = TimeInterval(timestamp) 13 let date = Date(timeIntervalSince1970: timeInterval) 14 return date 15 } 16 17 //获取两个日期的间隔天数 18 class func getDateInterval(dateA:Date,dateB:Date) ->Int{ 19 let interval = dateA.timeIntervalSince(dateB) 20 let days = Int(interval/(24*60*60)) 21 // let hours = Int(interval/(60*60)) 22 // let mins = Int(interval/60) 23 return days 24 } 25 } 最后就是方法的调用与后台的输出 1 let date = Date() 2 print(date.getDateString()) 3 print(date.getDateWeekday()) 4 print(date.getTimeStamp()) 5 6 let dateA = Utility.getDateFromTimestamp(1507605071) 7 let dateB = Utility.getDateFromTimestamp(1507877163) 8 let days = Utility.getDateInterval(dateA: dateA, dateB: dateB) 9 print(days) PS: http://tool.chinaz.com/Tools/unixtime.aspx 这个网址可以在线转换时间戳 |
请发表评论