Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to change year in Date in Swift #54

Open
onmyway133 opened this issue Jun 9, 2017 · 2 comments
Open

How to change year in Date in Swift #54

onmyway133 opened this issue Jun 9, 2017 · 2 comments
Labels

Comments

@onmyway133
Copy link
Owner

onmyway133 commented Jun 9, 2017

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)
@HasaanAli
Copy link

This is damn right.

@amardon
Copy link

amardon commented Jan 4, 2019

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 onmyway133 changed the title Changing year in Date in Swift How to change year in Date in Swift May 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants