Swift之家

Swift获取系统当前时间

2017-11-30  本文已影响67人  小小土豆dev

GMT:格林威治标准时间

UTC:全球标准时间

系统当前时间:以GMT时间为标准,计算的当前时间

获取当前系统时间

1、创建一个时间对象

let today = Date()// 获取格林威治时间(GMT)/ 标准时间

print("today = \(today)")// 打印出的时间是GTM时间,比北京时间早了8个小时

2、获取当前时区

let zone = NSTimeZone.system

print("zone = \(zone)")

3、获取当前时区和GMT的时间间隔

let interval = zone.secondsFromGMT()

print("interval = \(interval)")// 当前时区和格林威治时区的时间差 8小时 = 28800秒

4、获取当前系统时间

let now = today.addingTimeInterval(TimeInterval(interval))

print("now = \(now)")// 是Date格式不是String

时间戳

概念:时间戳是从 1970年1月1号 00:00:00(北京时间1970年01月01日08时00分00秒)开始到当前时间走过的毫秒数

获取当前系统时间的时间戳

// GMT时间转时间戳 没有时差,直接是系统当前时间戳

let timeInterval = Date().timeIntervalSince1970

获取比当前时间,晚5秒的时间

let nowLater = Date.init(timeIntervalSinceNow: 60)// 比GMT时间晚1分钟

let formTime = nowLater.timeIntervalSinceNow// 这里是以GMT标准时间为准

// nowLater 比GMT时间晚60秒

print("formTime = \(formTime)")

将 Date 转为 String

let dateformatter = DateFormatter()

dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss"// 自定义时间格式

let time = dateformatter.string(from: Date())

print("time = \(time)")// 当前系统时间

两个时间的间隔

思路:

1.将要对比的时间转换为时间戳(下面有转换的方法)

2.然后对比时间戳,记录时间戳差值(时间戳单位是毫秒)

3.然后就可以根据需求,将时间戳差值,转换为天,小时,分钟等

倒计时功能:通常是服务器会给我们返回一个时间戳,我们用这个时间戳和当前系统的时间戳对比,将对比的差值(毫秒)转换为几天,几小时等。

下面是常用的几个时间方法:

1、获取当前系统时间

func currentTime() -> String {

  let dateformatter = DateFormatter()

  dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss"// 自定义时间格式

  // GMT时间 转字符串,直接是系统当前时间

  return dateformatter.string(from: Date())

}

2、获取当前系统时间的时间戳

func currentTimeStamp() -> TimeInterval {

  let date = Date()

  // GMT时间转时间戳 没有时差,直接是系统当前时间戳

  return date.timeIntervalSince1970

}

3、时间戳 -> 日期

func timeStampToString(_ timeStamp: TimeInterval) -> String {

  let date = NSDate(timeIntervalSince1970: timeStamp)

  let dateformatter = DateFormatter()

  dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss"// 自定义时间格式

  return dateformatter.string(from: dateasDate)

}

4、日期 -> 时间戳

func stringToTimeStamp(_ time: String) -> TimeInterval {

  let dateformatter = DateFormatter()

  dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss"// 自定义时间格式

  let date = dateformatter.date(from: time)

  return (date?.timeIntervalSince1970)!

}

5、时间比较

fun ccompareDate(_ date1: Date, date date2: Date) -> Int {

    let result = date1.compare(date2)

    switch result {

    case .orderedDescending:// date1 小于 date2

    return 1

    case .orderedSame:// 相等

    return 0

    case .orderedAscending:// date1 大于 date2

    return -1

    }

}

上一篇下一篇

猜你喜欢

热点阅读