DEV Community

Khoa Pham
Khoa Pham

Posted on

3 1

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay