swift 4.2如何正确检查已过去的时间

问题描述 投票:0回答:3

我需要在从服务器下载/操作一些数据之前检查一个日期。假设我需要在24小时或更长时间内完成此操作。这段代码似乎有效,但是我不确定,没有办法用更少的代码行完成它?对我来说似乎太长了。我检查了this,但解决方案与我的完全不同。

import UIKit


//standard day formatter
let dateFormatter = DateFormatter()



//let's say this is the date I saved last time i updated data from online server:
let previousDate: String = "2019-03-19 06:40 PM"
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
let old = dateFormatter.date(from: previousDate)

//today I try to download data
let today = Date()

//this simply tests if "moment before" is greater than "moment after"
if today > old! {
    print("update data")
} else {
    print("do not update")
}




//here I create a measure
let minute:TimeInterval = 60.0
let hour:TimeInterval = 60.0 * minute
let day:TimeInterval = 24 * hour

//here I measure if the old date added of 24h is greater than now, in that case a day or more is passed and I can update
let theOldDateMore24h = Date(timeInterval: day, since: old!)

if theOldDateMore24h < today {
    print("passed more than a day: Update!")
} else {
    print("less than a day, do not update")
}
swift nsdate nsdateformatter
3个回答
0
投票

Calendar有一种方法

func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents


获取day组件并检查大于0

let dateFormatter = DateFormatter()
let previousDate = "2019-03-19 06:40 PM"
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
let old = dateFormatter.date(from: previousDate)

//today I try to download data
let today = Date()

if let validDate = old, Calendar.current.dateComponents([.day], from: validDate, to: today).day! > 0 {
    print("passed more than a day: Update!")
} else {
    print("less than a day, do not update")
}

0
投票

快速扩展功能,以简化它:

extension Date {
    func isWithin(_ distanceTime: TimeInterval, after laterDate: Date) -> Bool{
        let distance = timeIntervalSince(laterDate)
        let result = distanceTime >= distance
        return result
    }
}

//Usage
let secondsInDay = TimeInterval(60 * 60 * 24)
let isUpToDate = Date().isWithin(secondsInDay, after: previousDate)

if !isUpToDate {
    print("passed more than a day: Update!")
}
else {
    print("less than a day, do not update")
}

0
投票

您实际上可以使用扩展名。它将返回所需的日历组件

延期

extension Date {

    func interval(ofComponent comp: Calendar.Component, fromDate date: Date) -> Int {

        let currentCalendar = Calendar.current

        guard let start = currentCalendar.ordinality(of: comp, in: .era, for: date) else { return 0 }
        guard let end = currentCalendar.ordinality(of: comp, in: .era, for: self) else { return 0 }

        return end - start
    }
}

用法

let yesterday = Date(timeInterval: -86400, since: Date())
let tomorrow = Date(timeInterval: 86400, since: Date())

// Change the component to your preference
let difference = tomorrow.interval(ofComponent: .day, fromDate: yesterday) // returns 2
© www.soinside.com 2019 - 2024. All rights reserved.