Skip to content

Commit

Permalink
Fixing issue malcommac#696 - Is it possible to round to seconds?
Browse files Browse the repository at this point in the history
  • Loading branch information
spneshaei committed Jul 6, 2021
1 parent 6190d0c commit 8d38795
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Sources/SwiftDate/DateInRegion/DateInRegion+Create.swift
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,8 @@ public extension DateInRegion {
/// - Returns: rounded date
func dateRoundedAt(_ style: RoundDateMode) -> DateInRegion {
switch style {
case .to1Sec: return dateRoundedAt(.toSecs(1))
case .to1Min: return dateRoundedAt(.toMins(1))
case .to5Mins: return dateRoundedAt(.toMins(5))
case .to10Mins: return dateRoundedAt(.toMins(10))
case .to30Mins: return dateRoundedAt(.toMins(30))
Expand Down Expand Up @@ -352,6 +354,24 @@ public extension DateInRegion {
let value = -((Int(1.minutes.timeInterval) * remain) + second)
return dateByAdding(value, .second)


case .toSecs(let secondInterval):
let onesDigit: Int = (second % 10)
if onesDigit < 5 {
return dateRoundedAt(.toFloorSecs(secondInterval))
} else {
return dateRoundedAt(.toCeilSecs(secondInterval))
}

case .toCeilSecs(let secondInterval):
let remain: Int = (second % secondInterval)
let value = (( Int(1.seconds.timeInterval) * (secondInterval - remain)) - nanosecond)
return dateByAdding(value, .nanosecond)

case .toFloorSecs(let secondInterval):
let remain: Int = (second % secondInterval)
let value = -((Int(1.seconds.timeInterval) * remain) + nanosecond)
return dateByAdding(value, .nanosecond)
}
}

Expand Down
5 changes: 5 additions & 0 deletions Sources/SwiftDate/Supports/Commons.swift
Original file line number Diff line number Diff line change
Expand Up @@ -236,18 +236,23 @@ public extension Calendar.Component {
/// Rounding mode for dates.
/// Round off/up (ceil) or down (floor) target date.
public enum RoundDateMode {
case to1Sec
case to1Min
case to5Mins
case to10Mins
case to30Mins
case toMins(_: Int)
case toSecs(_: Int)
case toCeil5Mins
case toCeil10Mins
case toCeil30Mins
case toCeilMins(_: Int)
case toCeilSecs(_: Int)
case toFloor5Mins
case toFloor10Mins
case toFloor30Mins
case toFloorMins(_: Int)
case toFloorSecs(_: Int)
}

/// Related type enum to get derivated date from a receiver date.
Expand Down

0 comments on commit 8d38795

Please sign in to comment.