iOS Swift 时间的一些方法

2,956 阅读1分钟

From:www.jianshu.com/p/41368a8c2…

1. 根据一个时间字符串转换任意样式

extension String {
    
    func formatDate() -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.current
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        guard let formatDate = dateFormatter.date(from: self) else { return "" }
        let calendar = Calendar.current
        _ = calendar.component(.era, from: formatDate)
        let year = calendar.component(.year, from: formatDate)
        let month = calendar.component(.month, from: formatDate)
        let day = calendar.component(.day, from: formatDate)
        let hour = calendar.component(.hour, from: formatDate)
        let minute = calendar.component(.minute, from: formatDate)
        let second = calendar.component(.second, from: formatDate)
        return String(format: "%.2zd年%.2zd月%.2zd日 %.2zd时:%.2zd分:%.2zd秒", year, month, day, hour, minute, second)
    }
} 
案列:
let dateString = "2018-08-25 20:00:00"
debugPrint(dateString.formatDate()) // "2018年08月25日 20时:00分:00秒" 

2. 获取星期几

extension String {
    
    func featureWeekday() -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.current
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        guard let formatDate = dateFormatter.date(from: self) else { return "" }
        let calendar = Calendar.current
        let weekDay = calendar.component(.weekday, from: formatDate)
        switch weekDay {
        case 1:
            return "星期日"
        case 2:
            return "星期一"
        case 3:
            return "星期二"
        case 4:
            return "星期三"
        case 5:
            return "星期四"
        case 6:
            return "星期五"
        case 7:
            return "星期六"
        default:
            return ""
        }
    }
} 
案列
let dateString = "2018-08-25 20:00:00"
debugPrint(dateString.featureWeekday()) // "星期六"