DEV Community

loading...

Changing year in Date in Swift

onmyway133 profile image Khoa Pham ・1 min read

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()

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)

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)

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)

Discussion

pic
Editor guide