0

I have spent almost a week with unsuccessful tries. How do I get the last date of the current month. For example if it is February in non-leap year then the last date of the month must be 28. How do get the '28'. Another example: If it is January then the last date must be '31'

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Dr.IDH
  • 23
  • 1
  • 3
  • In c# or vb.net I simply get the current month, and make a new date for the 1st of that month. Then I subtract 1 day, to get last day of the month. – David P Feb 14 '17 at 18:15

1 Answers1

8

There are many ways, here are two of them:

Get next 1. and subtract one day

func lastDayOfMonth1() -> Date
{
   let calendar = Calendar.current
   let components = DateComponents(day:1)
   let startOfNextMonth = calendar.nextDate(after:Date(), matching: components, matchingPolicy: .nextTime)!
   return calendar.date(byAdding:.day, value: -1, to: startOfNextMonth)!
}

print(lastDayOfMonth1())

Use range(of:in:for:) to get the last day from the range and set the components accordingly:

func lastDayOfMonth2() -> Date
{
    let calendar = Calendar.current
    let now = Date()
    var components = calendar.dateComponents([.year, .month, .day], from: now)
    let range = calendar.range(of: .day, in: .month, for: now)!
    components.day = range.upperBound - 1
    return calendar.date(from: components)!
}

print(lastDayOfMonth2())
vadian
  • 274,689
  • 30
  • 353
  • 361