Reputation: 477
I'm using a package call DateToolsSwift. Now, whenever I want to add a day to a Date object, I would do like this
let date = Date().add(TimeChunk(seconds: 0, minutes: 0, hours: 0, days: 3, weeks: 0, months: 0, years: 0))
This code is too long and it does't feel right. So my question is, is this the way to do it in DateToolsSwift? Or I'm doing it wrong?
Upvotes: 2
Views: 1120
Reputation: 3973
If you want an extended possibility to add any time you want in one shoot
extension Date {
public enum DateElement {
case seconds(Int)
case minutes(Int)
case hours(Int)
case days(Int)
case months(Int)
case years(Int)
}
public func add(_ time: DateElement...) -> Date? {
var dateComponent = DateComponents()
for e in time {
switch e {
case .seconds(let seconds):
dateComponent.second = seconds
case .minutes(let minutes):
dateComponent.minute = minutes
case .hours(let hours):
dateComponent.hour = hours
case .days(let days):
dateComponent.day = days
case .months(let months):
dateComponent.month = months
case .years(let years):
dateComponent.year = years
}
}
return Calendar.current.date(byAdding: dateComponent, to: self)
}
}
let somewhereLater = Date().add(.hours(2), .days(5), .months(1))
Upvotes: 0
Reputation: 3499
*Without using DateToolsSwift. For example, if you want to add 3 days to Jan 1, 1970
let aDate = Date(timeIntervalSince1970: 0)
var dateComponent = DateComponents()
dateComponent.day = 3
let next3Days = Calendar.current.date(byAdding: dateComponent, to: aDate)
Similarly, you can set aDate = Date()
if you want to add days to today.
EDIT
Alternatively, from @CodeDifferent
let next3Days = Calendar.current.date(byAdding: .day, value: 3, to: aDate)!
Upvotes: 7
Reputation: 539765
The DateToolsSwift package defines extension methods in Integer+DateTools.swift which allow the simple creation of
TimeChunk
s, e.g. 3.days
or 2.weeks
. Therefore you can do
let date = Date().add(3.days)
or, since DateToolsSwift also defines a custom +
operator,
let date = Date() + 3.days
Upvotes: 3