Read more about my blog https://github.com/onmyway133/blog/issues/54
Today I am trying to change the year of a Date object to 2000 in Swift.
let date = Date()
Firstly, I tried with date(bySetting:) , but it does not work from last year. It just returns nil
Calendar.current.date(bySetting: .year, value: 2000, of: date)
Secondly, I tried with dateComponents . component.year has changed, but the calendar still returns the original date, very strange !!. No matter what time zone and calendar I use, it still has this problem.
var component = calendar.dateComponents(in: TimeZone.current, from: base) component.year = year Calendar.current.date(from: component)
Finally, I tried to be more explicit, and it works 🎉
var component = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: base) component.year = year Calendar.current.date(from: component)
onmyway133
source share