Swift

Swift中日期类型的分类

2019-07-11  本文已影响3人  Coder东

//
//  NSDate+Helper.swift
//  SwiftChat
//
//  Created by 随风流年 on 2019/7/11.
//  Copyright © 2019 随风流年. All rights reserved.
//

import UIKit

extension NSDate {
    ///日期转字符串
    class func stringWithFormat(format:String,date:Date) -> String{
        let dateFormatter = DateFormatter.init()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: date)
    }
    /// 字符串转日期
    class func dateWithFormat(format:String,dateString:String) -> Date{
        let df = DateFormatter()
        df.dateFormat  = format
        return df.date(from: dateString)!
    }
    /// 返回当前日期是哪一年
    func yearIndex(date:Date) -> Int {
        let calendar = Calendar.current
        let timeZone = TimeZone.init(identifier: "UTC")
        let components = calendar.dateComponents(in: timeZone!, from: date)
        return components.year!
    }
    /// 返回每个月的天数
    class func daysOfMonth(date:Date) -> Int
    {
        let calendar = Calendar.current
        let range = calendar.range(of: Calendar.Component.day, in: Calendar.Component.month, for: date)
        return (range?.count)!
    }
    
    class func getWeekdayOfDate(date:Date) -> Int
    {
        let calendar = Calendar.current
        let timeZone = TimeZone.init(identifier: "UTC")
        let components = calendar.dateComponents(in: timeZone!, from: date)
        return components.weekday!-1 //从星期日开始,也就是星期天是1 星期一是2 ……星期六是7
    }
    //比较两天是否是同一天
    class func isSameDay(date1:Date, date2:Date) -> Bool
    {
        let calendar = Calendar.current
        let timeZone = TimeZone.init(identifier: "UTC")
        let components1 = calendar.dateComponents(in: timeZone!, from: date1)
        let components2 = calendar.dateComponents(in: timeZone!, from: date2)
        
        return components1.year == components2.year && components1.month == components2.month && components1.day == components2.day
    }
    
    class func getDateWithYear(year:Int, month:Int, day:Int) -> Date
    {
        var components = DateComponents.init()
        components.year = year
        components.month = month
        components.day = day
        
        let calendar = Calendar.current
        let date = calendar.date(from: components)
        return date!
    }

}
上一篇下一篇

猜你喜欢

热点阅读