How to get Monday's date of the current week in swift

前端 未结 8 1711
死守一世寂寞
死守一世寂寞 2020-11-29 05:36

I\'m trying to get Monday\'s date of the current week. This is treated as the first day of the week in my table view. I also need to get Sunday\'s of the current week. This

相关标签:
8条回答
  • 2020-11-29 06:03

    Addition to @Saneep answer

    If you would like to get exact dateTime as per given/current date (lets say you wanted to convert Monday's dateTime -> 23-05-2016 12:00:00 to 23-05-2016 05:35:17) then try this:

    func convertDate(date: NSDate, toGivendate: NSDate) -> NSDate {
        let calendar = NSCalendar.currentCalendar()
        let comp = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: toGivendate)
        let hour = comp.hour
        let minute = comp.minute
        let second = comp.second
    
        let dateComp = calendar.components([.Year, .Month, .Day], fromDate: date)
        let year = dateComp.year
        let month = dateComp.month
        let day = dateComp.day
    
        let components = NSDateComponents()
        components.year = year
        components.month = month
        components.day = day
        components.hour = hour
        components.minute = minute
        components.second = second
    
        let newConvertedDate = calendar.dateFromComponents(components)
    
        return newConvertedDate!
    }
    
    0 讨论(0)
  • 2020-11-29 06:06

    simple code (remember to take better care of the optionals):

    let now = Date()
    
    var calendar = Calendar(identifier: .gregorian)
    
    let timeZone = TimeZone(identifier: "UTC")!
    
    let desiredWeekDay = 2
    
    let weekDay = calendar.component(.weekday, from: now)
    var weekDayDate = calendar.date(bySetting: .weekday, value: desiredWeekDay, of: now)!
    
    /// Swift will give back the closest day matching the value above so we need to manipulate it to be always included at cuurent week.
    if weekDayDate > now, weekDay > desiredWeekDay {
        weekDayDate = weekDayDate - 7*24*60*60
    }
    
    print(weekDayDate)
    
    0 讨论(0)
提交回复
热议问题