最近处理了一些关于日期的问题,先记下来,可以后来查用。
1,将字符串转化为日期
let formatter = DateFormatter.init()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let lastTime = formatter.date(from:lastTimeString!)
2,将日期转化为字符串
let date = Date()
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let currentTime = timeFormatter.string(from: date as Date) as String
3,得到两个日期的差值
a,通过和格林威治时间比较,得到向差的秒数
let lastTime = formatter.date(from:lastTimeString!)
let currentTime = formatter.date(from:self.getCurrentTimeStamp())
let timeInterval = (currentTime?.timeIntervalSince1970)! - (lastTime?.timeIntervalSince1970)!
b,通过比较,得到相差的年月日时分秒
let ctime = date
let mtime = date2
let ctimedf = DateFormatter()
ctimedf.dateFormat = "yyyy-MM-dd HH:mm:ss"
let ctimeDate = ctimedf.date(from: ctime)
let mtimeDate = ctimedf.date(from: mtime)
let calendar = Calendar.current
let unitFlags:NSCalendar.Unit = [NSCalendar.Unit.year, NSCalendar.Unit.month , NSCalendar.Unit.day , NSCalendar.Unit.hour , NSCalendar.Unit.minute , NSCalendar.Unit.second]
let components = (calendar as NSCalendar).components(unitFlags, from: ctimeDate!, to: mtimeDate!, options: NSCalendar.Options.init(rawValue: 0))
components.hour!
components.day
components.second
components.minute!
4,获取当前时间的时分秒
let calendar: Calendar = Calendar(identifier: .gregorian)
var comps: DateComponents = DateComponents()
comps = calendar.dateComponents([.year,.month,.day, .weekday, .hour, .minute,.second], from: Date())
let hour = comps.hour! // 小时
let minutes = comps.minute! // 分钟
网友评论