How to change year in Date in Swift
Issue #54
Today I’m trying to change the year of a Date
object to 2000 in Swift.
1 | let date = Date() |
Firstly, I tried with date(bySetting:)
but it does not work with past year. It simply returns nil
1 | Calendar.current.date(bySetting: .year, value: 2000, of: date) |
Secondly, I tried with dateComponents
. The component.year
has changed, but it calendar
still returns the original date, very strange !!. No matter what timezone and calendar I use, it still has this problem
1 | var component = calendar.dateComponents(in: TimeZone.current, from: base) |
Finally, I tried to be more explicit, and it works 🎉
1 | var component = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: base) |