UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Week identifier in Calendar.current

Forums > Swift

Confucius once said: "Dates are hard. Like, really hard!" Or it was Mr. Hudson, can't remember.

Speaking of inconsistencies. For example, I want to get a range from today till the end of the month:

let calendar = Calendar.current
let date = Date()
let interval = calendar.dateInterval(of: .month, for: date)!
let days = calendar.dateComponents([.day], from: Date.now, to: interval.end).day!

It works as expected, it gives me a number. Great! Now let's get the same thing for a week:

let calendar = Calendar.current
let date = Date()
let interval = calendar.dateInterval(of: .weekOfYear, for: date)!
let days = calendar.dateComponents([.day], from: Date.now, to: interval.end).day!

It runs, but returns me nothing. What's wrong? Also, what's the difference between .weekOfYear and .weekOfMonth?

2      

I can't help you with your specific question. But I can tell you that the documentation says

"This value is interpreted in the context of the calendar in which it is used."

There are many different calendars you can use and some of the components have probably no use in a given calendar. That could be the reason why they're optionals.

2      

When you say "it returns me nothing", what exactly do you mean? You are force unwrapping the result of the call to dateComponents(_:from:to:) so if the result is nil you would get a crash, yet you didn't say it crashed, just that it returned nothing.

Your code works for me and returns the expected values.

3      

This is hilarious. I'm totally failed.

I lived my whole life in the country with .iso8601 calendar, and couple of years ago moved to the country with .gregorian calendar, and expecting to receive "2" today. This is shameful. I must apologize for wasting your time, guys.

2      

This is shameful. I must apologize for wasting your time, guys.

Not a waste of time!


We all learned something from your troubles. It would be fantasic if you added some comments, and a bit more code then posted it so the rest of us have a nice example to paste into our HackingWithSwift Playground notebook! We're a community, share your new knowledge with us!

Please mark your answer as Solved.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.