移动 前端 Python Android JavaiOS第三方资料收集iOS Developer

Swift-日历相关01

2017-04-03  本文已影响1061人  张不二01

1, 日历的基本知识

//MARK: 日历的基本知识
fileprivate func calendarBasic(){

    var calendar = Calendar.current
    calendar.locale = Locale.init(identifier: "zh_CN")

    //let currentDate = Date.init()
    //let timeInterval = TimeZone.current.secondsFromGMT(for: currentDate)
    print(calendar.timeZone)
    print(Date.init())
    
    //Date.init()是默认的值,是格林威治的标准时间,如果需要本地话,可以用formatter格式一下即可

    /*
    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "yyy-MM-dd HH:mm:ss.S Z" //(格式可按自己需求修整)
    let strNowTime = timeFormatter.string(from: Date.init()) as String
    print(strNowTime)
     */

    /*历标示符
     identifier 的范围可以是:
     NSCalendarIdentifierGregorian         公历
     NSCalendarIdentifierBuddhist          佛教日历
     NSCalendarIdentifierChinese           中国农历
     NSCalendarIdentifierHebrew            希伯来日历
     NSCalendarIdentifierIslamic           伊斯兰日历
     NSCalendarIdentifierIslamicCivil      伊斯兰教日历
     NSCalendarIdentifierJapanese          日本日历
     NSCalendarIdentifierRepublicOfChina   中华民国日历(台湾)
     NSCalendarIdentifierPersian           波斯历
     NSCalendarIdentifierIndian            印度日历
     NSCalendarIdentifierISO8601           ISO8601
     */
    // 获取地区信息标示符
    let calendarIdentifier = calendar.identifier
    print(calendarIdentifier)//gregorian代表公历

    // 获取地区信息
    let calendarLocalIdentifier = calendar.locale?.identifier
    print(calendarLocalIdentifier ?? "calendarLocalIdentifier is nil")

    // 获取时区信息
    let calendarTimeZone = calendar.timeZone
    print(calendarTimeZone)

    //获取每周的第一天从星期几开始
    let firstWeekDay = calendar.firstWeekday
    print(firstWeekDay)//1代表sunday,周日

    // 获取第一周必须包含的最少天数
    let minDaysInFirstWeek = calendar.minimumDaysInFirstWeek
    print(minDaysInFirstWeek)
}

2, DateComponents的基本知识

//MARK: DateComponents的基本知识
fileprivate func dateComponents(){

    //1, 可以手动创建components,然后进行自定义赋值,还可以将components转换成date对象
    var components = DateComponents.init()
    components.day = 35
    components.month = 5
    components.year = 2004
    components.weekday = 4
    components.hour = 30

    let weekday = components.weekday
    print(weekday ?? "weekday is nil")

    //这里默认的是0时区
    let gregorian = Calendar.init(identifier: .gregorian)//公历日历
    let customDate = gregorian.date(from: components)
    print(customDate ?? "customeDate is nil")
    //只需要用DateFormatter格式化一下就可以成为我们当前的8时区
    let formatter = DateFormatter.init()
    formatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"
    let theDate = formatter.string(from: customDate!)
    print(theDate)

    //2, 也可将日期转化成dateComponents
    let nowTime = Date.init()
    let calendar = Calendar.current
    let component = calendar.component(.second, from: nowTime)
    print(component)
    let componentsSet = Set<Calendar.Component>([.year, .month, .day, .hour, .minute, .second])
    let componentss = calendar.dateComponents(componentsSet, from: nowTime)
    print(componentss)

    var birthDayComponents = DateComponents.init()
    birthDayComponents.month = 2
    birthDayComponents.day = 7

    let birthday = gregorian.date(from: birthDayComponents)
    let theBirthday = formatter.string(from: birthday!)

    print("birthday is \(theBirthday)")
}

3,日历切换

//MARK: 日历切换
fileprivate func calendarSwitch(){
    let date = Date.init()
    let dateFormatter = DateFormatter.init()
    dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"
    let formatedDate = dateFormatter.string(from: date)
    print(formatedDate)

    //切换到中国农历(如果之前有创建其他日历,需要先把之前到日历给释放或者清空)
    let chinese = Calendar.init(identifier: .chinese)
    let components = Set<Calendar.Component>([.year, .month, .day, .hour, .minute, .second])
    let theComponents = chinese.dateComponents(components, from: date)
    print("阴历的日期是:\(theComponents)")
}

4,当前日期加上一定时间

//MARK: 当前日期加上一定时间
fileprivate func addCertainTime(){
    let todayTime = Date.init()
    let calendar = Calendar.current

    var offSetComponents = DateComponents.init()
    offSetComponents.hour = 2

    let adjustTime = calendar.date(byAdding: offSetComponents, to: todayTime)

    let dateFormatter = DateFormatter.init()
    dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"

    let theAdjustTime = dateFormatter.string(from: adjustTime!)

    print(theAdjustTime)
}

5, 获取当前周中的周日日期

//MARK: 获取当前周中的周日日期,这个暂时没有看懂,待会重新看一下另外一个教程里面的
fileprivate func getSundayFromCurrentWeek(){

    let todayTime = Date.init()
    let calendar = Calendar.current

    let weekDayComponents = calendar.dateComponents(Set<Calendar.Component>([.weekday]), from: todayTime)

    var componentsToSubtract = DateComponents.init()
    componentsToSubtract.day = 0 - (weekDayComponents.weekday! - 1)

    let beginningOfWeek = calendar.date(byAdding: componentsToSubtract, to: todayTime)


    let dateFormatter = DateFormatter.init()
    dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"
    let theBeginningOfWeek = dateFormatter.string(from: beginningOfWeek!)

    print(theBeginningOfWeek)
}

6, 计算出一周中的第一天,或周末第一天,或一月中第一天,一年中第一天等

//MARK: 计算出一周中的第一天,或周末第一天,或一月中第一天,一年中第一天
fileprivate func getFirstDayFromWeek(){
    let dateFormatter = DateFormatter.init()
    dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"

    let dateStr = "2017年05月08日 10时03分25秒 +0800"
    let date = dateFormatter.date(from: dateStr)

    let calendar = Calendar.current

    /*得到该日期的开始时间,也就是凌晨零点
    let date = calendar.startOfDay(for: todayDate)
    print(date)
    */

    /*获取周末开始时间
    var beginningOfWeekend: Date = Date.init()
    var interval: TimeInterval = 0
    let ok = calendar.dateIntervalOfWeekend(containing: date!, start: &beginningOfWeekend, interval: &interval)
    if ok == true{
        let theBeginningOfWeekend = dateFormatter.string(from: beginningOfWeekend)
        print("本周日开始日期是:\(theBeginningOfWeekend)")
    }else{
        print("给值不是周末")
    }*/

    //获取本周的第一天
    var beginningOfWeek: Date = Date.init()
    var interval01:TimeInterval = 0
    let ok01 = calendar.dateInterval(of: .weekOfMonth, start: &beginningOfWeek, interval: &interval01, for: date!)

    if ok01 == true{
        let thebeginningOfWeek = dateFormatter.string(from: beginningOfWeek)
        print(thebeginningOfWeek)
    }else{
        print("失败")
    }
}

7, 获取两个日期之间的间隔,通过日历计算,其实之前已经算过

//MARK: 获取两个日期之间的间隔,通过日历计算,其实之前已经算过了
fileprivate func calcTheIntervalBetweenTwoDate(){
    let dateFormatter = DateFormatter.init()
    dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"

    //第一个日期设置成当前日期好了
    let firDate = Date.init()

    //第二个日期随手设置一个
    let secDateStr = "2017年04月05日 10时03分25秒 +0800"
    let secDate = dateFormatter.date(from: secDateStr)

    let calendar = Calendar.current
    let timeInterval = calendar.dateComponents(Set<Calendar.Component>([.year, .month, .day, .hour, .minute, .second]), from: firDate, to: secDate!)

    print(timeInterval)
}

8, 计算同一时代的相差的天数

//MARK: 计算同一时代的相差的天数//-(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate
fileprivate func calcDaysBetweenTwoDate(){
    let startDateStr = "2017年04月05日 10时03分25秒 +0800"

    let endDteStr = "2017年05月30日 10时03分25秒 +0800"

    let dateFormatter = DateFormatter.init()
    dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"

    let startDate = dateFormatter.date(from: startDateStr)
    let endDate = dateFormatter.date(from: endDteStr)

    let calendar = Calendar.current

    //在同一个时代的天数
    let startDay = calendar.ordinality(of: .day, in: .era, for: startDate!)
    let endDay = calendar.ordinality(of: .day, in: .era, for: endDate!)

    //这里默认是月中的天数
    //let startDay = calendar.component(.day, from: startDate!)
    //let endDay = calendar.component(.day, from: startDate!)

    print(startDay ?? "startDay is nil", endDay ?? "endDay is nil")
    let daysBeweenTwoDate = endDay!-startDay!
    print(daysBeweenTwoDate)
}

9,计算不同时代相差的天数

//MARK: 计算不同时代相差的天数//-(NSInteger) daysFromDate:(NSDate *) startDate toDate:(NSDate *) endDate
fileprivate func calcDaysBetweenTwoDateInDifEra(){

    let startDateStr = "2017年04月05日 10时03分25秒 +0800"

    let endDteStr = "2017年05月30日 10时03分25秒 +0800"//我这里其实日期定的还是同时代

    let dateFormatter = DateFormatter.init()
    dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"

    let startDate = dateFormatter.date(from: startDateStr)
    let endDate = dateFormatter.date(from: endDteStr)

    let calendar = Calendar.current
    var startCompnents = calendar.dateComponents(Set<Calendar.Component>([.era, .year, .month, .day]), from: startDate!)
    var endCompnents = calendar.dateComponents(Set<Calendar.Component>([.era, .year, .month, .day]), from: endDate!)

    startCompnents.hour = 12
    endCompnents.hour = 12

    let date01 = calendar.date(from: startCompnents)
    let date02 = calendar.date(from: endCompnents)

    let daysBetweenTwoDateInDifEra = calendar.dateComponents(Set<Calendar.Component>([.day]), from: date01!, to: date02!)
    print(daysBetweenTwoDateInDifEra)
}

10,判断某个时期是否在本周范围内

//MARK: 判断某个时期是否在本周范围内
fileprivate func isDateInCurrentWeek(){

    let todayDate = Date.init()
    let localInterval: TimeInterval = TimeInterval(TimeZone.current.secondsFromGMT(for: todayDate))

    let dateFormatter = DateFormatter.init()
    dateFormatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒 Z"
    let dateStr = "2017年04月08日 18时03分25秒 +0800"
    let date = dateFormatter.date(from: dateStr)

    let calendar = Calendar.current
    var beginningOfWeek: Date = Date.init()
    var weekInterval: TimeInterval = 0
    let localTodayDate = todayDate.addingTimeInterval(localInterval)
    print(localTodayDate)

    let getCurrentWeek = calendar.dateInterval(of: .weekOfMonth, start: &beginningOfWeek, interval: &weekInterval, for: localTodayDate)

    if getCurrentWeek == true{
        let localBeginningOfWeek = beginningOfWeek.addingTimeInterval(localInterval)

        print("本周的开始时间是\(localBeginningOfWeek)")
        let theWeekInterval = self.getHHMMSSFormSS(seconds: Int(weekInterval))
        print("本周的时长是\(theWeekInterval)")
    }

    let dateInSecs = date?.timeIntervalSinceReferenceDate
    let beginningOfWeekInSecs = beginningOfWeek.timeIntervalSinceReferenceDate
    if dateInSecs! > beginningOfWeekInSecs && dateInSecs! < beginningOfWeekInSecs + weekInterval{
        print("是在本周范围内")
    }else{
        print("不在本周范围内")
    }
}
上一篇下一篇

猜你喜欢

热点阅读