dynamically create date for previous sunday at 12:00 AM

前端 未结 4 984
鱼传尺愫
鱼传尺愫 2021-01-14 16:13

I\'m struggling to figure out how to dynamically create a date object for the most previous sunday at 12:00 AM

I was thinking I could get today\'s date and then subt

4条回答
  •  Happy的楠姐
    2021-01-14 16:22

    @AndreasLey solution in Swift 2.0:

      func getLastSunday() -> NSDate?
    {
        let today = NSDate();
        let calendar : NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
        calendar.locale = NSLocale(localeIdentifier: "en-US") // force US locale, because other countries (e.g. the rest of the world) might use different weekday numbering
    
        let flags : NSCalendarUnit = [.Year , .Month, .Weekday, .WeekOfMonth, .Minute , .Second]
        let nowComponents = calendar.components(flags, fromDate: today)
    
        nowComponents.weekday = 1 //Sunday
        nowComponents.hour = 0  // 12:00 AM = midnight (12:00 PM would be 12)
        nowComponents.minute = 0
        nowComponents.second = 0;
    
    
        let  previousSunday = calendar.dateFromComponents(nowComponents);
        return previousSunday
    }
    

提交回复
热议问题