-2

whenever i use this method it always shows wrong date.

func startOfMonth() -> Date {
    let calendar = Calendar.current
    let currentDateComponents = calendar.dateComponents([.year, .day, .month], from: self)
    return calendar.date(from: currentDateComponents) ?? Date()
} 

Output:

2018-10-31 18:30:00 +0000

I want:

2018-11-1 18:30:00 +0000

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
jaskiratjd
  • 729
  • 1
  • 6
  • 16
  • 1
    That is the _correct_ date. You need to format it in order to display it in your time zone. – Sweeper Nov 01 '18 at 11:00
  • 1
    Whats the purpose of `?? Date()` Just force unwrap the result. `return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: self))!` – Leo Dabus Nov 01 '18 at 11:07
  • @Sweeper The date is correct only because today is the first day of the month. His method shouldn't get the day component from the original date. – Leo Dabus Nov 01 '18 at 11:16

1 Answers1

1

If you are willing to get the first day of the month you should not get the day component from the original date:

extension Date {
    var startOfMonth: Date {
        return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: self))!
    }
}

Date().startOfMonth.description(with: .current) //  "Thursday, November 1, 2018 at 12:00:00 AM Brasilia Standard Time"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571