Skip to content

Instantly share code, notes, and snippets.

@taybenlor
Created July 20, 2015 08:28
Show Gist options
  • Save taybenlor/a6ad125ca8130b8978be to your computer and use it in GitHub Desktop.
Save taybenlor/a6ad125ca8130b8978be to your computer and use it in GitHub Desktop.
Make dates nicer, very quick hack
//
// NicerDates.swift
//
// Created by Ben Taylor on 20/07/2015.
//
import Foundation
extension Int {
func days() -> NSDateComponents {
var components = NSDateComponents()
components.day = self
return components
}
func day() -> NSDateComponents {
return days()
}
func weeks() -> NSDateComponents {
var components = NSDateComponents()
components.day = 7*self
return components
}
func week() -> NSDateComponents {
return weeks()
}
func months() -> NSDateComponents {
var components = NSDateComponents()
components.month = self
return components
}
func month() -> NSDateComponents {
return months()
}
func years() -> NSDateComponents {
var components = NSDateComponents()
components.year = self
return components
}
func year() -> NSDateComponents {
return years()
}
func am() -> NSDateComponents {
return hours()
}
func pm() -> NSDateComponents {
return (self + 12).hours()
}
func hours() -> NSDateComponents {
var components = NSDateComponents()
components.hour = self
return components
}
func hour() -> NSDateComponents {
return hours()
}
}
extension NSDateComponents {
func fromNow() -> NSDate {
return fromDate(NSDate())
}
func fromDate(date: NSDate) -> NSDate {
let calendar = NSCalendar.currentCalendar()
return calendar.dateByAddingComponents(self, toDate: date, options: NSCalendarOptions.allZeros)!
}
}
extension NSDate {
func onSunday() -> NSDate {
let calendar = NSCalendar.currentCalendar()
var dateComponents = calendar.components((.WeekdayCalendarUnit | .WeekOfMonthCalendarUnit | .MonthCalendarUnit | .YearCalendarUnit | .HourCalendarUnit), fromDate: self)
dateComponents.weekday = 7
return calendar.dateFromComponents(dateComponents)!
}
func at(hourDateComponents: NSDateComponents) -> NSDate {
let calendar = NSCalendar.currentCalendar()
var dateComponents = calendar.components((.WeekdayCalendarUnit | .WeekOfMonthCalendarUnit | .MonthCalendarUnit | .YearCalendarUnit | .HourCalendarUnit), fromDate: self)
dateComponents.hour = hourDateComponents.hour
return calendar.dateFromComponents(dateComponents)!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment