Why is this returning nil

Hi, this code is returning nil always. So frustrating!
Code Block
let today = Date()
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.weekday], from: today)
let nineThirtyToday = Calendar.current.date(
bySettingHour: 90,
minute: 30,
second: 0,
of: today)
print(nineThirtyToday as Any)
if components.weekday == 4 {
if today <= nineThirtyToday! {
if UDM.shared.widgetDefaults?.value(forKey: "currentRiddle") as! String == currentRiddleFinal {
currentRiddleFinal = "Waiting for update from server"
}
}else {
print("Not Nine Thirty")
}
}
UDM.shared.widgetDefaults?.setValue(currentRiddleFinal, forKey: "currentRiddle")
print("Current Riddle: \(currentRiddleFinal)")
}

Thanks in advance!
Answered by Claude31 in 665789022
Error is
bySettingHour : 90

Should be

bySettingHour : 9
There are no return statement in the shown code, so returning nil always does not make sense.

Please explain what is nil.
I want it to be if before 9:30 on Wednesdays it says waiting for server to update. However it prints nil and crashes when I force unwrap it.

it prints nil

Your code has several prints, which one prints nil?

I want it to be if before 9:30

Why are you using 90 for hours?
Accepted Answer
Error is
bySettingHour : 90

Should be

bySettingHour : 9
Thanks, but now the nineThirtyToday print is printing:

Nine Thirty Output Optional(2021-03-10 17:30:00 +0000)

Which is 5:30pm. Any ideas?

Which is 5:30pm. Any ideas?

Default description of Date uses UTC as TimeZone. If you want to show it in the device TimeZone, you need to use DateFormatter.
Where would I put that?

Where would I put that?

If you are showing the date just for debugging, you usually do not use DateFormatter and calculate the time difference between UTC and your region.

I guess 17:30 UTC is 09:30 of your region, no? Then your code works as you expect.

Only when you need to create a string representation for users, you need DateFormatter to convert Date to String.


If you do want to use DateFormatter even for debugging output, you can write something like this:
Code Block
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.weekday], from: today)
let nineThirtyToday = calendar.date(
bySettingHour: 9,
minute: 30,
second: 0,
of: today)
let df = DateFormatter()
df.timeZone = TimeZone.current
df.dateStyle = .short
df.timeStyle = .short
print(df.string(from: nineThirtyToday ?? Date.distantPast))

(I recommend you to use the same calendar instance when getting components and nineThirtyToday to get consistent values.)
Thank you so much for your help!
Why is this returning nil
 
 
Q