You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
varcomponent= 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 🎉
varcomponent= calendar.dateComponents([.year,.month,.day,.hour,.minute,.second], from: base)
component.year = year
Calendar.current.date(from: component)
The text was updated successfully, but these errors were encountered:
I had the same issue. The problem with your second try is the component yearForWeekOfYear that stayed at the previous year. Setting it at the year you want or nil will make it work
onmyway133
changed the title
Changing year in Date in Swift
How to change year in Date in Swift
May 9, 2019
Today I'm trying to change the year of a
Date
object to 2000 in Swift.Firstly, I tried with
date(bySetting:)
but it does not work with past year. It simply returns nilSecondly, I tried with
dateComponents
. Thecomponent.year
has changed, but itcalendar
still returns the original date, very strange !!. No matter what timezone and calendar I use, it still has this problemFinally, I tried to be more explicit, and it works 🎉
The text was updated successfully, but these errors were encountered: