UIKit - Calendar components return absolute value for a negative year

Viewed 100

I'm having trouble with extracting the year from a Date. Everything works fine until I use a date that has a negative year. Then UIKit's Calendar.componten(:from:) returns the absolute value instead and is even off by 1. Here's an example:

import UIKit

let calendar = Calendar.current

let date = Date(timeIntervalSince1970: -90000000000)
print(date) // -0882-01-14 08:00:00 +0000
print(calendar.component(.year, from: date)) // 883

Any idea why that happens and how to correctly get the date without manually trying to figure out the year's sign?

Thanks!

1 Answers

Negative years should be present as B.S 9000 not "- 9000". In Swift there is era instance property as well. You can create your calendar and play with the values For example :

var newCalendar = Calendar(identifier: .gregorian)
newCalendar.timeZone = newCalendarTimeZone

let newCalendarEra = newCalendar.ordinality(of: .day, in: .era, for: now)
Related