Home > Software engineering >  Date range betwen now and end of the day and next day and end of the next day
Date range betwen now and end of the day and next day and end of the next day

Time:10-08

I'm trying to make a DatePicker with a choice between today and tomorrow. Two buttons to switch Date Range.

How to make today range? i. e. Now -> End of the day

How to make tomorrow range? i. e. Start of the next day -> End of the next day

what i've tried, but it's not correct

 var todayRange: ClosedRange<Date> {
    let calendar = Calendar.current
    var endComponents = DateComponents()
    endComponents.day = 1

    let endDate = calendar.date(byAdding: endComponents, to: Date.now)!
    return Date.now ... endDate
}

var tommorowRange: ClosedRange<Date> {
    let calendar = Calendar.current
    var startComponents = DateComponents()
    startComponents.day = 2
    var endComponents = DateComponents()
    endComponents.day = 1

    let startDate = calendar.date(byAdding: startComponents, to: Date.now)!
    let endDate = calendar.date(byAdding: endComponents, to: startDate)!
    return startDate ... endDate
}

CodePudding user response:

You're close.

I would suggest:

  • Get the start of day for today
  • Add 1 day
  • Subtract 0.001 seconds.

That will give you the end of today.

Here is some sample code.

let today = Date.now
let startOfToday = Calendar.current.startOfDay(for: today)
let oneDay = DateComponents(day: 1)
guard let tomorrow = Calendar.current.date(byAdding: oneDay, to: startOfToday) else { fatalError() }

let endOfToday = tomorrow.advanced(by: -0.001)
let endOfTodayString = DateFormatter.localizedString(from: endOfToday, dateStyle: .medium, timeStyle: .medium)
print("End of today = "   endOfTodayString)

guard let endOfTomorrow = Calendar.current.date(byAdding: oneDay, to: endOfToday) else { fatalError() }
let endOfTomorrowString = DateFormatter.localizedString(from: endOfToday, dateStyle: .medium, timeStyle: .medium)
print("End of tomorrow = "   endOfTomorrowString)

In my locale (US), on October 7th, that generates:

End of today = Oct 7, 2022 at 11:59:59 PM

End of tomorrow = Oct 7, 2022 at 11:59:59 PM

  • Related