简体   繁体   中英

Swift: How to display one of the two Images depending of the current time of the day

I have images named open and close, which are displayed according to the store timings. According to Indian Standard time the store timings are 11Am to 11PM, during this time I want to display the open image and closed image in the remaining time. Can someone help me how to do it. Thanks.

First of all, get current time in hours (it is 24 hour format)

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour], fromDate: date)
let hour = components.hour

Then check for time

if hour >= 11 && hour <= 22 {
    // show open image
}
else {
    // show close image
}
var component: NSDateComponents = NSCalendar.currentCalendar().components([.Hour, .Minute], fromDate: currentDate)
var strStoreStatus: String = (component.hour() >= 11 && component.hour() <= 22) ? "OPEN" : "CLOSE"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM