首先说明一下,在ios中获取到的时区是计算过夏令时的,比如:在以华盛顿(美国)为例,时区为西五区,获取后为西四区,安卓中获取到的为西五区;通过和安卓对比后得出的结果。
相关时间之间的转化代码如下:
/// DEBUG下打印方法(normal)
/// - Parameter items: 打印内容
static func Dlog(_ items: @autoclosure () -> Any) {
#if DEBUG
print(items())
#endif
}
/// 获取时间的类型
enum RequestTimeType {
/// yyyy-MM-dd HH:mm:ss
case TimeNormal
/// yyyy-MM-dd HH:mm:ss.SSS
case TimeMSNormal
/// 时间戳
case TimeStamp
/// yyyy-MM-dd
case TimeYYYYMMdd
/// yyyy-MM-dd HH:mm:ss ZZZZ
case TimeAndTimeZone
}
// MARK:获取时间戳和时区
/// 获取时间戳和时区
static func requestTimeStampAndTimeZone() -> (Int,String) {
let timeStamp = Date().timeIntervalSince1970 // 获取时间戳
let systemTimezone = NSTimeZone.system
let tempTZ = systemTimezone.abbreviation()!
GlobalTools.Dlog("****时间戳:\(Int(timeStamp))\n****时区:\(tempTZ)")
GlobalTools.Dlog("GMT:\(systemTimezone.secondsFromGMT(for: Date()))\noffset:\(systemTimezone.daylightSavingTimeOffset())")
GlobalTools.Dlog("原始时间:\(Date())")
// 过滤掉GMT
let timeZone = tempTZ.replacingOccurrences(of: "GMT", with: "")
return (Int(timeStamp),timeZone)
}
/// 时间戳解析(时间戳加时区转换成时间戳后转成相关类型的时间)----return String(传入的数据不符合标准将返回空)
/// - Parameters:
/// - time: 时间戳加时区
/// - timeType: 需要转成的时间类型
static func timeStampParsing(time : String,timeType : RequestTimeType) -> String {
var timeStamp : TimeInterval = 0
// 判断给的字符串是否大于10位数
if time.count >= 10 {
// 截取前10个字符
let tempTimeStamp = time.prefix(10)
// 判断截取后的字符串是否是数字
if GlobalTools.authNumber(content: String(tempTimeStamp)) {
timeStamp = TimeInterval(tempTimeStamp)!
} else {
return ""
}
} else {
return ""
}
let date = Date(timeIntervalSince1970: timeStamp)
let dateFormatter = DateFormatter()
switch timeType {
case .TimeMSNormal:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
case .TimeStamp:
return "\(timeStamp)"
case .TimeNormal:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
case .TimeYYYYMMdd:
dateFormatter.dateFormat = "yyyy-MM-dd"
case .TimeAndTimeZone:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ"
}
let time = dateFormatter.string(from: date)
GlobalTools.Dlog("Time---->\(time)")
return time
}
/// 时间年月日等转时间戳
/// - Parameters:
/// - time: 需要转的时间
/// - timeType: 时间类型
static func timeStringToInterval(time : String,timeType : RequestTimeType) -> TimeInterval {
let dateFormatter = DateFormatter()
switch timeType {
case .TimeMSNormal:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
case .TimeStamp:
return 0
case .TimeNormal:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
case .TimeYYYYMMdd:
dateFormatter.dateFormat = "yyyy-MM-dd"
case .TimeAndTimeZone:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZ"
}
let date = dateFormatter.date(from: time)
let timeStamp = date?.timeIntervalSince1970
GlobalTools.Dlog("Date--->\(date!)************TimeStamp--->\(timeStamp!)")
return timeStamp!
}
网友评论