Devan Devan - 4 months ago 6
Swift Question

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.

Answer

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
}
Comments