Stack Overflow Asked by ios on November 4, 2021
I a working in swift 4, I have a scenario is rounding the time to nearest 5 minutes (like 11:12 AM – 11:15 AM). I am able to do that for this mentioned scenario. But here my problem is I should not round the time when it is "11:15 AM". Can anyone please help me to resolve this issue.Thanks in Advance.Please find my below code..
func getTimesData{
let date = Date()
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let dateString = df.string(from: date)
let convertedDate = dateString.convertingStringToDate(date: dateString)
let roundedDate = convertedDate.rounded(minutes: 5, rounding: .ceil) //Here I am rounding the time.
let dateAdded = roundedDate.addingTimeInterval(5 * 180)
}
The below code I am using for round the time which I get from StackOverFlow itself.
enum DateRoundingType {
case round
case ceil
case floor
}
extension Date {
func rounded(minutes: TimeInterval, rounding: DateRoundingType = .round) -> Date {
return rounded(seconds: minutes * 60, rounding: rounding)
}
func rounded(seconds: TimeInterval, rounding: DateRoundingType = .round) -> Date {
var roundedInterval: TimeInterval = 0
switch rounding {
case .round:
roundedInterval = (timeIntervalSinceReferenceDate / seconds).rounded() * seconds
case .ceil:
roundedInterval = ceil(timeIntervalSinceReferenceDate / seconds) * seconds
case .floor:
roundedInterval = floor(timeIntervalSinceReferenceDate / seconds) * seconds
}
return Date(timeIntervalSinceReferenceDate: roundedInterval)
}
}
There is no need to "bake" the date first using a DateFormatter, instead call the rounding function directly.
let rounded = Date().rounded(minutes: 5, rounding: .ceil)
If you have an issue with 11:15 not being rounded to 11:15 that is probably because the seconds aren't exactly 0 so I would suggest using the default .round
instead.
let rounded = Date().rounded(minutes: 5)
Answered by Joakim Danielson on November 4, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP