You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.8 KiB

//
// Date+DateTools.swift
// DateTools
//
// Created by Grayson Webster on 8/17/16.
// Copyright © 2016 Grayson Webster. All rights reserved.
//
import Foundation
/**
* Extends the Date class by adding convenient initializers based on components
* and format strings.
*/
public extension Date {
6 years ago
// MARK: - Initializers
6 years ago
/**
* Init date with components.
*
* - parameter year: Year component of new date
* - parameter month: Month component of new date
* - parameter day: Day component of new date
* - parameter hour: Hour component of new date
* - parameter minute: Minute component of new date
* - parameter second: Second component of new date
*/
6 years ago
init(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int) {
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = hour
dateComponents.minute = minute
dateComponents.second = second
6 years ago
6 years ago
guard let date = Calendar.current.date(from: dateComponents) else {
self = Date()
return
}
self = date
}
6 years ago
/**
* Init date with components. Hour, minutes, and seconds set to zero.
*
* - parameter year: Year component of new date
* - parameter month: Month component of new date
* - parameter day: Day component of new date
*/
6 years ago
init(year: Int, month: Int, day: Int) {
self.init(year: year, month: month, day: day, hour: 0, minute: 0, second: 0)
}
6 years ago
/**
* Init date from string, given a format string, according to Apple's date formatting guide, and time zone.
*
* - parameter dateString: Date in the formatting given by the format parameter
* - parameter format: Format style using Apple's date formatting guide
* - parameter timeZone: Time zone of date
*/
6 years ago
init(dateString: String, format: String, timeZone: TimeZone) {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .none
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = format
6 years ago
6 years ago
guard let date = dateFormatter.date(from: dateString) else {
self = Date()
return
}
self = date
}
6 years ago
/**
* Init date from string, given a format string, according to Apple's date formatting guide.
* Time Zone automatically selected as the current time zone.
*
* - parameter dateString: Date in the formatting given by the format parameter
* - parameter format: Format style using Apple's date formatting guide
*/
6 years ago
init(dateString: String, format: String) {
self.init(dateString: dateString, format: format, timeZone: TimeZone.autoupdatingCurrent)
}
}