DEV Community

Khoa Pham
Khoa Pham

Posted on

Changing year in Date in Swift

Original post https://github.com/onmyway133/blog/issues/54

Today I'm trying to change the year of a Date object to 2000 in Swift.

let date = Date()
Enter fullscreen mode Exit fullscreen mode

Firstly, I tried with date(bySetting:) but it does not work with past year. It simply returns nil

Calendar.current.date(bySetting: .year, value: 2000, of: date)
Enter fullscreen mode Exit fullscreen mode

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

var component = calendar.dateComponents(in: TimeZone.current, from: base)
component.year = year
Calendar.current.date(from: component)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)