I want to check if the current date input is 1 second away from new date (Date format: "2023-05-20T23:59:59.000+05:30"). Below is my Date extension.
extension Date {
var isOneSecondAway: Bool {
let calendar = Calendar.current
let nextStartOfDay = calendar.date(byAdding: .day, value: 1, to: self.startOfDay) ?? self
let timeIntervalInSeconds = Int(nextStartOfDay.startOfDay.timeIntervalSince(self))
return timeIntervalInSeconds == 1
}
var startOfDay: Date {
return Calendar.current.startOfDay(for: self)
}
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let targetDateString = "2023-05-20T23:59:59.000+05:30"
guard let targetDate = dateFormatter.date(from: targetDateString) else {return}
print(targetDate.isOneSecondAway)
Expected output for "2023-05-20T23:59:59.000+05:30" is true but its returning false. Am I doing something wrong here?
You need a timezone in order to figure out when the "start of day" is, and to a lesser extent, when the "next day" is.
You used
Calendar.currentin yourDateextensions, so the timezone ofCalendar.currentwill be used to do the date calculations. This is usually the system timezone. Note that aDateobject does not have an associated timezone.Calendardoes.I suspect that the timezone of
Calendar.currentisn't at an offset of +05:30 for the date and time that you used.If you set the timezone explicitly to be at an offset of +05:30, then the code prints
true:Of course, this wouldn't be very useful if your date strings can contain timezones other than +05:30.
To handle all kinds of timezones, the
Dateextensions need a timezone parameter, and you need to extract the timezone from the strings.Here I used a
TimeZoneinitialiser, adapted from this post.