如何找出上周的开始和结束日

时间:2016-07-04 17:16:38

标签: ios swift nsdate

为了找到当周的开始和结束,我设法做到了:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

如何更新此代码以获取上周的开始/结束?

2 个答案:

答案 0 :(得分:0)

// Getting first day of the previous week 
func getPreviousWeekStartDay() -> Date? {
    let gregorian = Calendar(identifier: .gregorian)
    let sunday = gregorian.date(from: 
    gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
    return gregorian.date(byAdding: .day, value: -7, to: sunday!)!
}

// Getting last day of previous week 
func getPreviousWeekEndDay() -> Date? {        
    let gregorian = Calendar(identifier: .gregorian)
    let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
    return gregorian.date(byAdding: .day, value: -1, to: sunday!)!
}

答案 1 :(得分:-3)

您可以从一周前开始计算:

let weekInSeconds: Double = 60 * 60 * 24 * 7
calendar.rangeOfUnit(.WeekOfMonth, startDate: &startOfWeek, interval: &interval, forDate: NSDate(timeIntervalSinceNow: -weekInSeconds))

现在,您可以使用weekInSeconds的倍数(未来几周为正,过去几周为负,本周为0)控制您希望在过去的哪一周(从现在开始)查看。