Date(时间)扩展

时间转换经常用到,如下是累积的一些方法:

1. 基本转换方法
extension Date {
// 毫秒级
static func timeIntervalToDateString(msec interval: TimeInterval, _ format: String) -> String {
    guard interval > 0 else {return ""}
    let timeInterval: TimeInterval = interval / 1000
    let date: Date = Date(timeIntervalSince1970: timeInterval)
    return date.dateString(format)
}

// 秒级
static func timeIntervalToDateString(sec interval: TimeInterval, _ format: String) -> String {
    guard interval > 0 else {return ""}
    let timeInterval: TimeInterval = interval
    let date: Date = Date(timeIntervalSince1970: timeInterval)
    return date.dateString(format)
}

// 现在
static func now(_ format: String) -> String {
    return Date().dateString(format)
}

// 昨天 or 昨天相对于今天的时间
static func yesterday(_ format: String) -> String {
    return dateString(before: 1, format)
}

// 今天之前某一天
static func dateString(before dayNumber: Int, _ format: String) -> String {
    let interval = Date().timeIntervalSince1970
    let beforeInterval = interval - TimeInterval(3600 * 24 * dayNumber)
    let date = Date(timeIntervalSince1970: beforeInterval)
    
    return date.dateString(format)
}

// 今天之后某一天
static func dateString(after dayNumber: Int, _ format: String) -> String {
    let interval = Date().timeIntervalSince1970
    let beforeInterval = interval + TimeInterval(3600 * 24 * dayNumber)
    let date = Date(timeIntervalSince1970: beforeInterval)
    
    return date.dateString(format)
}

// 获取指定日期所在周的任意 weekDay 的日期 //
// weekDay  -  1~7 '周一'~'周日'
func dateString(_ weekDay: Int, _ format: String) -> String {
    let calendar = Calendar.current
    var components = calendar.dateComponents([.year, .month, .day, .weekday], from: self)
    if let week_day = components.weekday, let day = components.day {
        var diff = 0
        if week_day == 1 { // 默认 1 是 周日
            diff = weekDay - 7
        }else { // 2 ~ 7  -  '周一' ~ '周六'
            diff = weekDay - (week_day - 1)
        }
        
        components.setValue(day + diff, for: .day)
        if let date_goal: Date = calendar.date(from: components) {
            return date_goal.dateString(format)
        }
    }
    
    return ""
}

func dateString(_ format: String) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = format
    return formatter.string(from: self)
}

static func timeInterval(_ dateStr: String, _ format: String) -> TimeInterval {
    var interval: TimeInterval = 0
    
    if let date = date(dateStr, format) {
        interval = date.timeIntervalSince1970
    }
    
    return interval
}

static func todayTimeInterval() -> TimeInterval {
    var interval: TimeInterval = 0
    
    let dateStr = Date().dateString("yyyy-MM-dd")
    
    if let date = date(dateStr, "yyyy-MM-dd") {
        interval = date.timeIntervalSince1970
    }
    
    return interval
}

static func date(_ str: String, _ format: String) -> Date? {
    let formatter = DateFormatter()
    formatter.dateFormat = format
    return formatter.date(from: str)
}
}
2. 时间比较
extension Date {
/// 小于今天
static func dateLessThanToday(_ time: TimeInterval, _ format: String) -> Bool {
    let s_s: String = timeIntervalToDateString(msec: time, format)
    let s: TimeInterval = timeInterval(s_s, format)
    let o: TimeInterval = timeInterval(Date.now(format), format)
    
    return s < o
}

/// 小于
static func dateLessThan(_ time: TimeInterval, _ other: TimeInterval, _ format: String) -> Bool {
    let s_s: String = timeIntervalToDateString(msec: time, format)
    let s: TimeInterval = timeInterval(s_s, format)
    let o_s: String = timeIntervalToDateString(msec: other, format)
    let o: TimeInterval = timeInterval(o_s, format)
    
    return s < o
}

/// 大于今天
static func dateMoreThanToday(_ time: TimeInterval, _ format: String) -> Bool {
    let s_s: String = timeIntervalToDateString(msec: time, format)
    let s: TimeInterval = timeInterval(s_s, format)
    let o: TimeInterval = timeInterval(Date.now(format), format)
    
    return s > o
}

/// 大于
static func dateMoreThan(_ time: TimeInterval, _ other: TimeInterval, _ format: String) -> Bool {
    let s_s: String = timeIntervalToDateString(msec: time, format)
    let s: TimeInterval = timeInterval(s_s, format)
    let o_s: String = timeIntervalToDateString(msec: other, format)
    let o: TimeInterval = timeInterval(o_s, format)
    
    return s > o
}
}
3. 时间的特殊展示
extension Date {
static func diffDateStr(_ dateStr: String, _ otherDateStr: String, _ format: String) -> String {
    let one = timeInterval(dateStr, format)
    let other = timeInterval(otherDateStr, format)
    
    let diff_day = fabs(one - other) / 24 / 3600
    
    return String(format: "%.1f天", diff_day)
}

/// 返回: *天前
static func beforeDay(_ dateStr: String, _ format: String) -> String {
    let date = timeInterval(dateStr, format)
    let now = Date().timeIntervalSince1970
    
    let s_day = Int(abs(date - now))
    
    if s_day < 60 {
        return "刚刚"
    }else if s_day < 3600 {
        return "\(s_day / 60)分钟前"
    }else if s_day < 24 * 3600 {
        return "\(s_day / 3600)小时前"
    }else if s_day < 30 * 24 * 3600 {
        return "\(s_day / 3600 / 24)天前"
    }else if s_day < 12 * 30 * 24 * 3600 {
        return "\(s_day / 3600 / 24 / 30)月前"
    }else {
        return "\(s_day / 3600 / 24 / 30 / 12)年前"
    }
}

static func smartTime(_ time: TimeInterval) -> String {
    let date = Date(timeIntervalSince1970: time / 1000)
    let diff_cmps = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date, to: Date())
    let format = DateFormatter()
    
    if diff_cmps.year == 0 { // 今年
        if diff_cmps.month == 0, diff_cmps.day == 1 { // 昨天
            format.dateFormat = "昨天 HH:mm"
            return format.string(from: date)
        }else if diff_cmps.month == 0, diff_cmps.day == 0 { // 今天
            if let h = diff_cmps.hour, h >= 1 {
                return "\(h)小时前"
            }else if let m = diff_cmps.minute, m >= 1 {
                return "\(m)分钟前"
            }else {
                return "刚刚"
            }
        }else { // 今年的其他日子
            format.dateFormat = "MM-dd HH:mm"
            return format.string(from: date)
        }
    }else { // 非今年
        format.dateFormat = "yyyy-MM-dd HH:mm"
        return format.string(from: date)
    }
}
}
4. 扩展后的扩展
extension Date {
enum PartitionType: String {
    case MiddleTransverseLine = "-"
    case Point = "."
    case ObliqueLine = "/"
    case none
}

/// 今天日期 // 年月日
static func today(_ type: PartitionType) -> String {
    switch type {
    case .MiddleTransverseLine:
        return now("yyyy-MM-dd")
    case .Point:
        return now("yyyy.MM.dd")
    case .ObliqueLine:
        return now("yyyy/MM/dd")
    case .none:
        return now("yyyyMMdd")
    }
}

/// 当前时间
static func now(_ type: PartitionType) -> String {
    switch type {
    case .MiddleTransverseLine:
        return now("yyyy-MM-dd HH:mm:ss")
    case .Point:
        return now("yyyy.MM.dd HH:mm:ss")
    case .ObliqueLine:
        return now("yyyy/MM/dd HH:mm:ss")
    case .none:
        return now("yyyyMMddHHmmss")
    }
}

/// 昨天日期
static func yesterday(_ type: PartitionType) -> String {
    switch type {
    case .MiddleTransverseLine:
        return yesterday("yyyy-MM-dd")
    case .Point:
        return yesterday("yyyy.MM.dd")
    case .ObliqueLine:
        return yesterday("yyyy/MM/dd")
    case .none:
        return yesterday("yyyyMMdd")
    }
}

/// 之后日期
static func after(_ dayNumber: Int, _ type: PartitionType) -> String {
    switch type {
    case .MiddleTransverseLine:
        return dateString(after: dayNumber, "yyyy-MM-dd")
    case .Point:
        return dateString(after: dayNumber, "yyyy.MM.dd")
    case .ObliqueLine:
        return dateString(after: dayNumber, "yyyy/MM/dd")
    case .none:
        return dateString(after: dayNumber, "yyyyMMdd")
    }
}

/// 之前日期
static func before(_ dayNumber: Int, _ type: PartitionType) -> String {
    switch type {
    case .MiddleTransverseLine:
        return dateString(before: dayNumber, "yyyy-MM-dd")
    case .Point:
        return dateString(before: dayNumber, "yyyy.MM.dd")
    case .ObliqueLine:
        return dateString(before: dayNumber, "yyyy/MM/dd")
    case .none:
        return dateString(before: dayNumber, "yyyyMMdd")
    }
}

/// 本周周一
static func firstWeekDay(_ type: PartitionType) -> String {
    switch type {
    case .MiddleTransverseLine:
        return Date().dateString(1, "yyyy-MM-dd")
    case .Point:
        return Date().dateString(1, "yyyy.MM.dd")
    case .ObliqueLine:
        return Date().dateString(1, "yyyy/MM/dd")
    case .none:
        return Date().dateString(1, "yyyyMMdd")
    }
}

static func dateFormat(_ type: PartitionType) -> String {
    switch type {
    case .MiddleTransverseLine:
        return "yyyy-MM-dd"
    case .Point:
        return "yyyy.MM.dd"
    case .ObliqueLine:
        return "yyyy/MM/dd"
    case .none:
        return "yyyyMMdd"
    }
}

static func timeFormat(_ type: PartitionType) -> String {
    switch type {
    case .MiddleTransverseLine:
        return "yyyy-MM-dd HH:mm:ss"
    case .Point:
        return "yyyy.MM.dd HH:mm:ss"
    case .ObliqueLine:
        return "yyyy/MM/dd HH:mm:ss"
    case .none:
        return "yyyyMMddHHmmss"
    }
}

static func cycleStr(_ num: Int) -> String {
    switch num {
    case 0:
        return "周日"
    case 1:
        return "周一"
    case 2:
        return "周二"
    case 3:
        return "周三"
    case 4:
        return "周四"
    case 5:
        return "周五"
    case 6:
        return "周六"
    case 7:
        return "周日"
    default:
        return ""
    }
}

static func cycleStr(_ str: String) -> String {
    var string = str
    
    string.replace("1", "周一")
    string.replace("2", "周二")
    string.replace("3", "周三")
    string.replace("4", "周四")
    string.replace("5", "周五")
    string.replace("6", "周六")
    string.replace("7", "周日")
    
    return string
}

/// 一周时间排序 str: "2,4,3,1"  +  spaceStr: ","  =  "周一,周二,周三,周四"
static func cycleSortStr(_ str: String, _ spaceStr: String) -> String {
    guard str.count > 0 else {return str}
    let intArr = str.components(separatedBy: spaceStr).map{ Int($0) ?? 0 }.sorted(by: { $0 < $1 })
    let string = intArr.map{ cycleStr($0)}.joined(separator: spaceStr)
    
    return string
}
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,701评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,649评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,037评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,994评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,018评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,796评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,481评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,370评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,868评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,014评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,153评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,832评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,494评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,039评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,437评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,131评论 2 356

推荐阅读更多精彩内容