0

Get last week and last month start and end dates.

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))

I need last week start date and end date[Start day is Monday and end day is sunday]

And last month start date and end date

Naresh
  • 16,698
  • 6
  • 112
  • 113
  • What you meant by **last week and last month start and end dates.** ?? – dahiya_boy Apr 10 '19 at 07:18
  • @dahiya_boy He wants 1/3/2019, 31/3/2019 and 31/3/2019, 6/4/2019 – RajeshKumar R Apr 10 '19 at 07:20
  • @ RajeshKumar R, yes you are right – Naresh Apr 10 '19 at 07:21
  • last month start and end dates https://stackoverflow.com/a/33606288/7250862 – RajeshKumar R Apr 10 '19 at 07:23
  • @RajeshKumar R, it's getting **Ambiguous use of 'components'** in this line let components = calendar.components([.Year, .Month], fromDate: date) My code is let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" let date = Date() let calendar = Calendar.current let components = calendar.components([.Year, .Month], fromDate: date) let startOfMonth = Calendar.dateFromComponents(components)! print(dateFormatter.stringFromDate(startOfMonth)) – Naresh Apr 10 '19 at 07:31

1 Answers1

1

You should use this function to calculate the range of dates, it takes a target date, a calendar component and two inout parameters that will be populated with the date and time interval calculated.

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

Here's an example:

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)
}

If you need to change the first day of the week you can change it in your calendar like this:

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

Remember that when you print the date print(startOfLastMonth), it is displayed in UTC, if you want the date printed in your timezone you will have to use a DateFormatter.

LorenzOliveto
  • 7,796
  • 1
  • 20
  • 47
  • your code working fine, but when I set date formatter it getting wrong last month last date. let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" print(dateFormatter.string(from: startOfLastMonth)) Output: 01-03-2019 00:00:00 01-04-2019 00:00:00 print(dateFormatter.string(from: endOfLastMonth)) – Naresh Apr 10 '19 at 09:21
  • 1
    Removing a second (or a day if you want the start of the day) from endOfLastMonth should give you the right date. let endOfLastMonth = startOfLastMonth.addingTimeInterval(interval-1) – LorenzOliveto Apr 10 '19 at 09:30
  • Thnak you, Result of call to 'dateInterval(of:start:interval:for:)' is unused Getting this warning in this line Calendar.current.dateInterval(of: .weekOfYear, start: &startOfLastWeek, interval: &interval, for: lastWeek) – Naresh Apr 10 '19 at 09:35
  • Except above warning your code working fine. Thank you. – Naresh Apr 10 '19 at 09:36
  • 1
    Yes this call returns a bool that indicates if the calculation was successful. If you need it you can assign it to a variable (let success = Calendar.current.dateInterval...) otherwise you can ignore the result adding _ = before the call (_ = Calendar.current.dateInterval...) – LorenzOliveto Apr 10 '19 at 09:39
  • 1
    @ lorenzoliveto, thank you very much to spent your valuable time for me. – Naresh Apr 10 '19 at 09:40
  • Last week code getting Sunday to Sunday, means 31-03-2019 and 7-04-2019. I need to change last week 1st day Monday ( 01-04-2019 and 7-04-2019) let lastWeek = Calendar.current.date(byAdding: .weekOfYear, value: -1, to: date) if let lastWeek = lastWeek { var startOfLastWeek = Date() var interval = TimeInterval(0) _ = Calendar.current.dateInterval(of: .weekOfYear, start: &startOfLastWeek, interval: &interval, for: lastWeek) let endOfLastWeek = startOfLastWeek.addingTimeInterval(interval) } – Naresh Apr 10 '19 at 11:29
  • How to change last week first day Monday onwards and last week last sunday. – Naresh Apr 10 '19 at 11:30
  • last week 1st day getting Sunday, I want to change it Monday. Can you please suggest. (Week starts with Monday and ends with sunday) – Naresh Apr 15 '19 at 13:18
  • @ LorenzOliveto, your code not working, can you help me to get last week date from Monday. My code is var dateFormatter:DateFormatter! var date:Date! In **viewDidLoad()** dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" – Naresh Apr 17 '19 at 06:40
  • My complete code in my function var calendar = Calendar.current calendar.firstWeekday = 2 // 1 is Sunday, 2 is Monday let lastWeek = calendar.date(byAdding: .weekOfYear, value: -1, to: Date()) if let lastWeek = lastWeek { var startOfLastWeek = Date() var interval = TimeInterval(0) _ = Calendar.current.dateInterval(of: .weekOfYear, start: &startOfLastWeek, interval: &interval, for: lastWeek) – Naresh Apr 17 '19 at 06:41
  • let endOfLastWeek = startOfLastWeek.addingTimeInterval(interval) let startWeekString = dateFormatter.string(from: startOfLastWeek) let endWeekString = dateFormatter.string(from: endOfLastWeek) – Naresh Apr 17 '19 at 06:41
  • Hello, this is not the way to ask questions on StackOverflow, open a new question so also others can see it and answer. – LorenzOliveto Apr 17 '19 at 06:53