iOS 时间工具

2,378 阅读1分钟
  1. 判断是否是24小时制
  • Android 有系统函数支持 DateFormat.is24HourFormat
  • iOS 没有系统函数支持,需要自己实现
public class func is24HourFormat() -> Bool {
    let dateFormat = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)
    if dateFormat?.range(of: "a") == nil {
        return true
    }
    
    return false
}
  1. 从 Date 读取小时、分钟
  • 通过 Calendar 类可以很方便的获取( 24 小时制的)小时、分钟、日期等各项属性
  • 24 小时制和 12 小时制互转
  • 24 小时制 0:00 ~ 23:59
  • 12 小时制 12AM ~ 1AM ~ 11AM ~ 12PM ~ 1PM ~ 11PM
// 24 小时制的小时
public class func getDateHour(date: Date) -> Int {
    return Calendar.current.component(.hour, from: date)
}

public class func getDateMinutes(date: Date) -> Int {
    return Calendar.current.component(.minute, from: date)
}
  1. 判断两个 Date 是否是同一天
public class func isSameDay(firstDate: Date, secondDate: Date) -> Bool {
    return Calendar.current.isDate(firstDate, inSameDayAs: secondDate)
}