Hi! I would like to make text appear based on the local time of the user. The idea is that when it's between 00:00:01 AM and 11:00:00 AM, that the text will say "breakfast" and that when it's between 11:00:00 AM and 03:00:00 PM, the text will say "lunch". Etc.
I found this code online but I can't get it working.
Can you help me? Possibly with other code?
.
Contentview:
struct Test: View {
var now = Date()
var breakfastTime = Date.parse("00:00:01")
var lunchTime = Date.parse("11:00:00")
var dinerTime = Date.parse("16:00:00")
func activeDinerCourse() -> String {
if now > breakfastTime && now < lunchTime {
return "Breakfast"
}
if now > lunchTime && now < dinerTime {
return "Lunch"
}
if now > dinerTime && now < Date.parse("23:59:59"){
return "Diner"
}
return "Something went wrong..."
}
var date = Date.now.formatted(date: .omitted, time: .shortened)
var body: some View {
VStack {
Text("\(date)")
Text(activeDinerCourse())
}
}
}
.
.Parse extention
public extension Date {
static func parse(_ string: String, format: String = "HH:mm:ss") -> Date {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone.default
dateFormatter.dateFormat = format
let date = dateFormatter.date(from: string)!
return date
}
func dateString(_ format: String = "HH:mm:ss") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
.
Thank you!