【问题标题】:Swift 5: Calculate current time is between 2 timesSwift 5:计算当前时间在 2 次之间
【发布时间】:2021-01-22 03:36:53
【问题描述】:

我不擅长 Swift 所以我想知道如何计算当前时间在两次之间。

我从后端得到以下响应。 {"workHours":"M-F 9:00 - 18:00"}

从上面的字符串中,如何编写一个类/结构(或另一种最佳方式)来验证今天的当前时间是否在描述的时间范围内("M-F 9:00 - 18:00")?

public final class DateValidator {
    let startTime: Date?
    let endTime: Date?
    
    func isInRange() -> Bool {
        // write modules here
        // How to validate
    }
    
    public init(dateString: String) {
        // dateString should be "M-F 9:00 - 18:00"
        // Extract startTime and endTime from dateString
    }
}

【问题讨论】:

标签: swift datetime timestamp nsdate


【解决方案1】:

设置 DateComponentsFormatter

let dcf = DateComponentsFormatter()
dcf.allowedUnits = [.day, .hour, .minute, .second]
dcf.unitsStyle = .full

设置普通日期格式化程序

let df = ISO8601DateFormatter()
df.formatOptions = [.withFullDate, .withDashSeparatorInDate]

执行格式化

if let future = df.date(from: "2019-04-29"), let diff = dcf.string(from: Date(), to: future) {
    print(diff)
}

输出是

3天6小时9分9秒

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多