获取上周和上个月的开始和结束日期

时间:2019-04-10 07:03:23

标签: ios swift date calendar

获取上周和上个月的开始和结束日期。

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let date = Date()

//Today date
let dateString = dateFormatter.string(from: date)
print(dateString)

//Yesterday
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: date)!
print(dateFormatter.string(from: yesterday))

//This week
let startWeek = date.startOfWeek
let endWeek = date.endOfWeek
print(startWeek ?? "not found start date")
print(endWeek ?? "not found end date")

extension Date {//Get this week starts from monday
var startOfWeek: Date? {
    let gregorian = Calendar(identifier: .gregorian)
    guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
    return gregorian.date(byAdding: .day, value: 2, to: sunday)
}

var endOfWeek: Date? {
    let gregorian = Calendar(identifier: .gregorian)
    guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
    return gregorian.date(byAdding: .day, value: 8, to: sunday)
}

}

//This month
dateFormatter.dateFormat = "MM-yyyy"
let nameOfMonth = dateFormatter.string(from: date)
print(nameOfMonth)

//Last 30days
let last30Days = Calendar.current.date(byAdding: .day, value: -30, to: date)!
print(dateFormatter.string(from: last30Days))

我需要上周的开始日期和结束日期[开始日期是星期一,结束日期是星期日]

以及上个月的开始日期和结束日期

1 个答案:

答案 0 :(得分:1)

您应该使用this函数来计算日期范围,它需要一个目标日期,一个日历组件和两个inout参数,其中将填充计算出的日期和时间间隔。

func dateInterval(of component: Calendar.Component, start: inout Date, interval: inout TimeInterval, for date: Date) -> Bool

这是一个例子:

let calendar = Calendar.current
let today = Date()

let lastWeek = calendar.date(byAdding: .weekOfYear, value: -1, to: today)
let lastMonth = calendar.date(byAdding: .month, value: -1, to: today)

if let lastWeek = lastWeek {
    var startOfLastWeek = Date()
    var interval = TimeInterval(0)

    calendar.dateInterval(of: .weekOfYear, start: &startOfLastWeek, interval: &interval, for: lastWeek)

    let endOfLastWeek = startOfLastWeek.addingTimeInterval(interval)

    print(startOfLastWeek)
    print(endOfLastWeek)
}

if let lastMonth = lastMonth {
    var startOfLastMonth = Date()
    var interval = TimeInterval(0)

    calendar.dateInterval(of: .month, start: &startOfLastMonth, interval: &interval, for: lastMonth)

    let endOfLastMonth = startOfLastMonth.addingTimeInterval(interval)

    print(startOfLastMonth)
    print(endOfLastMonth)
}

如果您需要更改一周的第一天,可以在日历中进行如下更改:

var calendar = Calendar.current
calendar.firstWeekday = 2 // 1 is Sunday, 2 is Monday

请记住,在打印日期print(startOfLastMonth)时,它以UTC显示,如果要在时区中打印日期,则必须使用DateFormatter