Search code examples
iosswiftdatensdatemonthcalendar

Get next 3rd month name from the current month in swift


How can I get The 3rd month names from Current month to Nov. Ex:-if the current month is Nov then I want the month names from Feb. Current month should be the running month.

Question: How to get 3rd month name from the current month?

Can someone please explain to me how to get month name. Any help would be greatly appreciated.

Thanks in advance.


Solution

  • You need to use the Calendar class, e.g.

    var now = Date()
    var calendar = Calendar.current
    
    
    if let then = calendar.date(byAdding: .month, value: 3, to: now) {
      let dateFormatter = DateFormatter()
      dateFormatter.dateFormat = "LLLL"
      let monthName = dateFormatter.string(from: then)
      print ("\(monthName)")
    }
    

    Just keep in mind how calenar arithmetics is handled: if you add "3 months" to let's say Nov 30th, 2019, then you'll get Feb-29th, 2020, although someone might expect March-01, 2020.