根据日期

时间:2016-04-04 08:20:46

标签: swift

我正在尝试根据它的日期显示某些东西的开放时间。像这样:

Opening Hours 
**Monday: 8:00-17:00**
Tuesday: 8:00-17:00
Wednesday: 8:00-17:00
Thursday: 8:00-17:00
Friday: 8:00-17:00
Saturday: 8:00-13:00
Sunday: closed

或只是显示

Monday: 8:00-17:00

我的假设是使用switch语句,但是我需要做些什么来找出它是什么日子?

4 个答案:

答案 0 :(得分:1)

您可以使用component(_:fromDate:)获取当前日期的工作日。那看起来像是:

let currentDay = NSCalendar.currentCalendar().component(.Weekday, fromDate:NSDate());

根据currentDay的值,您可以提供正确的营业时间。

答案 1 :(得分:1)

您可以使用NSCalendar.Weekday单位作为整数(星期日到星期六为格里高利历的1 ... 7)。

如果您知道星期几表示为Int,而不是使用switch语句,则可以在不同的开放时间使用[Int: String]字典。

let calendar = NSCalendar.currentCalendar()
let today = calendar.component(.Weekday, fromDate: NSDate())
    // Gregorian calendar: sunday = 0, monday = 1, ...

let openingHours: [Int: String] = [1: "Sunday: closed", 2: "Monday: 8:00-17:00", 3: "Tuesday: 8:00-17:00"] // ...

print("Opening hours:\n\(openingHours[today] ?? "")")  
/* Opening hours:
   Monday: 8:00-17:00 */

另一种方法是创建一个计算属性扩展名NSDate(),将当前工作日作为String

返回
extension NSDate {
    var weekday : String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "EEEE"
        return formatter.stringFromDate(self)
    }
}

这可以很容易地与[String: String]字典一起用于保存weekday : opening hours的集合:

/* example usage */
let openingHours: [String: String] =
    ["Sunday": "closed",
     "Monday": "8:00-17:00",
     "Tuesday": "8:00-17:00"] // ...

let today = NSDate().weekday
print("Opening hours:\n\(today): \(openingHours[today] ?? "")")
/* Opening hours:
   Monday: 8:00-17:00 */

答案 2 :(得分:1)

另一种解决方案可能是:

import Foundation

let today = NSDate()
let dateFormatter = NSDateFormatter()
let currentDay = NSCalendar.currentCalendar().component(.Weekday, fromDate:today);

dateFormatter.dateFormat = "EEEE"
let dayOfWeekString = dateFormatter.stringFromDate(today)

switch currentDay
{
case 2,3,4,5:
    print("\(dayOfWeekString): 8:00 - 17:00")

case 6:
    print("\(dayOfWeekString): 8:00 - 13:00")

default:
    print("\(dayOfWeekString): closed")
}

答案 3 :(得分:0)

我宁愿使用更通用的解决方案,而不是使用switch语句。这也是利用元组和类型别名来增强代码表现力和可读性的一个很好的演示。

typealias Time = (start: Int, end: Int)
// starting with Sunday
let openTimes: [Time] = [(0,0), (9,17), (9,17), (9,17), (9,17), (9,17), (9,12)]

let flags : NSCalendarUnit = [.Hour, .Weekday]

func isOpenAtTime(date: NSDate) -> Bool {
    let time = NSCalendar.currentCalendar().components(flags, fromDate: date)
    let openingHours = openTimes[time.weekday - 1]
    let hour = time.hour
    return hour >= openingHours.start && hour <= openingHours.end
}

你可能也想处理一些边缘情况,但你明白了 您可以使用分钟而不是数小时来更精细地完成此工作。