0

When I try to add a time interval to a given date at the end of some of the months, I get illogical results.

In the following example, when I add 5 hours to an 8:00PM time, in the given date, the resulted date will be the following at 1:00AM, which is expected. But if I add 6 hours instead of 5, the result will be the date after the following at 2:00AM, which completely doesn't make sense.

import SwiftUI

let calendar = Calendar(identifier: .islamic)
let formatter = DateFormatter()
formatter.calendar = calendar
formatter.dateFormat = "dd/MM/yyyy HH:mma"

let components = DateComponents(calendar: calendar, year: 1445, month: 7, day: 29, hour: 20, minute: 0, second: 0)
let givenDate = calendar.date(from: components)!
let after_5_hours = givenDate.advanced(by: 60 * 60 * 5)
let after_6_hours = givenDate.advanced(by: 60 * 60 * 6)

formatter.string(from: givenDate)      // = "29/07/1445 20:00PM"
formatter.string(from: after_5_hours)  // = "30/07/1445 01:00AM"
formatter.string(from: after_6_hours)  // = "01/08/1445 02:00AM"

Update: The behavior occurs while using islamic calendar. I couldn't reproduce it in gregorian calendar

16
  • Is the behavior different for different years? Commented Jul 5 at 18:37
  • Assalaam alykum! I have not use the .islamic calendar in iOS but I'm thinking, could it be that the FORMATTER also has to be set correctly, somehow ?
    – Fattie
    Commented Jul 5 at 18:39
  • Did you try the other formats of that command, like .date(byAdding: .day, value: ..etc It may lead to some finding.
    – Fattie
    Commented Jul 5 at 18:42
  • Exactly, use the same calendar instance for adding. calendar.date(byAdding: .hour, value: 5, to: givenDate)! Commented Jul 5 at 18:48
  • @ScottHunter the behavior is the same for some months in some years. I'm getting this results randomly
    – Mohammed
    Commented Jul 5 at 18:56

1 Answer 1

2

Using Calendar(identifier: .islamicCivil) fixes the problem.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.