Andrew Andrew - 4 months ago 20
Swift Question

Show/Hide label based on time of day

I am looking to have a label that is shown and hidden depending on the time of day. I am using this as a type of open sign at a store. Between the hours of 8 am - 5 pm Mon - Fri, the label displays, if not, the label is hidden. I can't exactly figure out how to compare to the current time and open hours in order to carry out the if/else statements. Also, I do not have an idea about the date but assume would be easy if the previous problem was solved.

Here is the code that I have. I did not add much becuase I know what I have is not going to work with the mktClock.stringValue >= "Time".

//Set time
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm:ss a zzz"
dateFormatter.timeZone = NSTimeZone(name: "US/Eastern")
dateString = dateFormatter.stringFromDate(date)
mktClock.stringValue = dateString as String

//Displays open if the market is open
if mktClock.stringValue >= "09:30:00 AM EDT" {
mktOpen.hidden = false
mktOpen.hidden = true


Try this:

func getDayOfWeek() -> Int {
    let todayDate = NSDate()
    let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    let myComponents = myCalendar?.components(.Weekday, fromDate: todayDate)
    let weekDay = myComponents?.weekday
    return weekDay!


Now to get your solution:

let dayOfWeek = getDayOfWeek()
if dayOfWeek > 1 && dayOfWeek < 7 {
    let hour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate())
    if hour > 8 && hour < 13 {
        mktOpen.hidden = false
    } else {
        //Before 8 or after 5
        mktOpen.hidden = true
} else {
    //Sunday or Saturday
    mktOpen.hidden = true

let hour credit: