How To Call Function On Specific Date

I'm trying to do an action in my app when it is a spcific date. Here is an "example"

if it is June 5, 2017 {

} else {

}

Obviously, the bold section won't work in Swift. That's the part that I'm trying to figure out. How would I accomplish this?

Replies

This is a tricky task, because you'll realize you don't know (or haven't said) what it is you really want to test.


A date like "June 5, 2017" is context sensitive. Do you mean local time? GMT? Do you want to test whether it's just become June 5 (after being June 4), or whether it's any time from 00:00:00 am to 11:59:59 pm? What calendar(s) can the date be specified in? What if the date doesn't exist in the calendar (some dates were skipped, historically, as part of various calendar reforms) or existed twice? If the date is a user entry, can it be invalid (e.g. Feb 30) by the time it gets to this "if" test?


In the simplest case, you can use DateComponents to specify a date, and use a time of 0:00:00, and have it convert to a Date value that represents the moment at the beginning of that day. Then do it again to get a second Date value that represents the beginning of the next day. Then get the current date/time — "Date ()" — and test whether it lies within the range:


     if currentDateTime >= yourDayDateTimeAtStart && currentDateTime < nextDayDateTimeAtStart …


Although it's a couple of years old now, you might get some insights from this WWDC video:


developer.apple.com/videos/play/wwdc2013/227/

Hi,


I created a small demo, might be helping you...


let currentDate = Date()
//define a startDate & time
var sDateComponents = DateComponents()
sDateComponents.year = 2017
sDateComponents.month = 05
sDateComponents.day = 18
sDateComponents.hour = 19
sDateComponents.minute = 15
sDateComponents.second = 0
//define an endDate & time
var eDateComponents = DateComponents()
eDateComponents.year = 2017
eDateComponents.month = 05
eDateComponents.day = 18
eDateComponents.hour = 21
eDateComponents.minute = 15
eDateComponents.second = 0
//create the startDate & endDate
let calendar = Calendar(identifier: .gregorian)
let startDate = calendar.date(from: sDateComponents)!
let endDate = calendar.date(from: eDateComponents)!
//check if the currentDate is between the specific dates-times
if startDate <= currentDate && currentDate <= endDate {
    print("Current date is in hardcoded date-interval")
} else {
    print("Current date is not relevant")
}


Have fun,

Joris