Skip to content

Instantly share code, notes, and snippets.

@loganwright
Created June 2, 2015 14:20
Show Gist options
  • Save loganwright/7a7a404a005788e04075 to your computer and use it in GitHub Desktop.
Save loganwright/7a7a404a005788e04075 to your computer and use it in GitHub Desktop.
A structure for holding and referencing the time of day
struct TimeOfDay {
// MARK: Public Properties
var hours: Int
var minutes: Int
var stringRepresentation: String {
var stringRepresentation = hours < 10 ? "0" : ""
stringRepresentation += "\(hours):\(minutes)"
return stringRepresentation
}
var displayString: String {
let dateFormatter = NSDateFormatter()
// Backing Format
dateFormatter.dateFormat = "HH:mm"
dateFormatter.timeZone = NSTimeZone.systemTimeZone()
dateFormatter.locale = NSLocale.currentLocale()
if let date = dateFormatter.dateFromString(stringRepresentation) {
// Display format
dateFormatter.dateFormat = "h:mm a"
return dateFormatter.stringFromDate(date)
} else {
return ""
}
}
// MARK: Initialization
init?(stringRepresentation: String) {
let components = stringRepresentation.componentsSeparatedByString(":")
if components.count == 2, let hours = components.first?.toInt(), let minutes = components.last?.toInt() {
self.hours = hours
self.minutes = minutes
} else {
return nil
}
}
init?(date: NSDate) {
let formatter = NSDateFormatter()
formatter.locale = NSLocale.currentLocale()
formatter.timeZone = NSTimeZone.systemTimeZone()
formatter.dateFormat = "HH:mm"
let formattedStringRepresentation = formatter.stringFromDate(date)
self.init(stringRepresentation: formattedStringRepresentation)
}
// MARK: Date Conversion
func timeToday() -> NSDate? {
return timeOnDate(NSDate())
}
func timeOnDate(date: NSDate) -> NSDate? {
let calendar = NSCalendar.currentCalendar()
let dateComponents: NSDateComponents = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute, fromDate: date)
dateComponents.hour = hours
dateComponents.minute = minutes
return calendar.dateFromComponents(dateComponents)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment