且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

制定一天的开始和结束。迅速

更新时间:2023-11-23 21:15:28

我们可以使用 NSCalendar 中的方法创建一个更通用的函数:

We can create a more generic function using the methods on NSCalendar:

func rangeOfPeriod(period: NSCalendarUnit, date: NSDate) -> (NSDate, NSDate) {
    let calendar = NSCalendar.currentCalendar()    
    var startDate: NSDate? = nil

    // let's ask calendar for the start of the period
    calendar.rangeOfUnit(period, startDate: &startDate, interval: nil, forDate: date)

    // end of this period is the start of the next period
    let endDate = calendar.dateByAddingUnit(period, value: 1, toDate: startDate!, options: [])

    // you can subtract 1 second if you want to make "Feb 1 00:00:00" into "Jan 31 23:59:59"
    // let endDate2 = calendar.dateByAddingUnit(.Second, value: -1, toDate: endDate!, options: [])

    return (startDate!, endDate!)
}

被称为

 print("\(rangeOfPeriod(.WeekOfYear, date: NSDate()))")
 print("\(rangeOfPeriod(.Day, date: NSDate()))")

将其放入代码中:

public class Date {
    let dateFormatter = NSDateFormatter()
    let date = NSDate()
    let calendar = NSCalendar.currentCalendar()

    func rangeOfPeriod(period: NSCalendarUnit) -> (NSDate, NSDate) {
        var startDate: NSDate? = nil

        calendar.rangeOfUnit(period, startDate: &startDate, interval: nil, forDate: date)

        let endDate = calendar.dateByAddingUnit(period, value: 1, toDate: startDate!, options: [])

        return (startDate!, endDate!)
    }

    func calcStartAndEndDateForWeek() {
        let (startOfWeek, endOfWeek) = rangeOfPeriod(.WeekOfYear)

        print("Start of week = \(dateFormatter.stringFromDate(startOfWeek))")
        print("End of the week = \(dateFormatter.stringFromDate(endOfWeek))")
    }


    func calcStartAndEndDateForDay() {
        let (startOfDay, endOfDay) = rangeOfPeriod(.Day)

        print("Start of day = \(dateFormatter.stringFromDate(startOfDay))")
        print("End of the day = \(dateFormatter.stringFromDate(endOfDay))")
    }

    init() {
        dateFormatter.dateFormat = "dd-MM-yyyy"
    }
}

let myDate = Date()
myDate.calcStartAndEndDateForWeek()
myDate.calcStartAndEndDateForDay()