Skip to content

Instantly share code, notes, and snippets.

@regnerjr
Last active August 29, 2015 14:17
Show Gist options
  • Save regnerjr/3c880e423df0c6de4101 to your computer and use it in GitHub Desktop.
Save regnerjr/3c880e423df0c6de4101 to your computer and use it in GitHub Desktop.
A Function for returning the next NSDate which matches given Day, Hour, Minute, Useful for getting an NSDate to represent Sunday at 4:00 am. This works no matter what the date is now.
import UIKit
import Swift
import XCPlayground
// we want to schedule a timer to fire on Sunday at 4:00am.
// NSTimer takes a fire date.
// NSTimer.init(fireDate date: NSDate, interval seconds: NSTimeInterval, target target: AnyObject, selector aSelector: Selector, userInfo userInfo: AnyObject?, repeats repeats: Bool)
//
// So how do we get the date for the next coming Sunday at 4:00am ?
// Date Components of course!
// Sunday, 4:00 am
let resetDay = 1
let resetHour = 4
let resetMinute = 0
func getDateFor(day: Int, hour: Int, minute: Int) -> NSDate? {
// Get the Calendar in use
let cal = NSCalendar.currentCalendar()
// Get the current day, Hour, Minute
let todaysComps = cal.components(
NSCalendarUnit.CalendarUnitWeekday |
NSCalendarUnit.CalendarUnitHour |
NSCalendarUnit.CalendarUnitMinute
, fromDate: NSDate())
todaysComps.weekday
todaysComps.hour
todaysComps.minute
// Get the relative components,
// This is where the real magic happens, How much time between now and our reset time
// in days hours minutes
let resetComps = NSDateComponents()
resetComps.day = day - todaysComps.day
resetComps.hour = hour - todaysComps.hour
resetComps.minute = minute - todaysComps.minute
// Taking the above differences, add them to now
let date = cal.dateByAddingComponents(resetComps, toDate: NSDate(),
options: NSCalendarOptions.MatchNextTime)
return date //an NSDate? which is the next sunday at 4:00am, useful for settign our timer with
}
let timerDate = getDateFor(resetDay, resetHour, resetMinute)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment