0

I need to check a date before downloading / manipulate some data from a server. Let's say I need to do that only if 24 hours or more are gone by. this code seems to work, but I'm not sure about it, no way to do it with less lines of code? it seems to be too long to me. i checked this but solutions are quite different from mine.

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")
}
biggreentree
  • 1,633
  • 3
  • 20
  • 35

3 Answers3

0

There is a method in Calendar

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


Get the day component and check greater than 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")
}
vadian
  • 274,689
  • 30
  • 353
  • 361
0

Quick extension function to simplify it:

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")
}
GetSwifty
  • 7,568
  • 1
  • 29
  • 46
  • 1
    Consider that days can have more or less than 86400 seconds when daylight saving time changes. – vadian Mar 20 '19 at 18:24
  • Usually I care, but it doesn't matter for this use case. It's an update function and the simplest (and fastest) solution for "Let's say I need to do that only if 24 hours or more are gone by." is a basic seconds calculation. – GetSwifty Mar 20 '19 at 18:26
0

You can actually use an extension for this. It will return the required calendar component

Extension

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

Usage

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
Stijnk008
  • 222
  • 3
  • 23