Round up current time to next 30 mins interval

橙三吉。 提交于 2021-02-16 22:42:38

问题


I want current time to round up to next 30 mins interval. Eg: If I open the app with current time as 8:33pm, I want next 30 mins round up time to be 9:00pm. If current time is May 22 11:30pm, next round up time should be May 23 00am.

I tried with below code, but that gives me the nearest round up which is 8:30pm.

How can I get next round up date and time?

func next30Mins() -> Date {
    return Date(timeIntervalSinceReferenceDate: (timeIntervalSinceReferenceDate / 1800.0).rounded(.toNearestOrEven) * 1800.0)
}

回答1:


You can get the date minute component, check if it is equal or more than 30 and return the nextDate with minute component equal to zero otherwise equal to 30:

extension Date {
    var minute: Int { Calendar.current.component(.minute, from: self) }
    var nextHalfHour: Date {
        Calendar.current.nextDate(after: self, matching: DateComponents(minute: minute >= 30 ? 0 : 30), matchingPolicy: .strict)!
    }
}

Date().nextHalfHour // "May 23, 2020 at 1:00 AM"


来源:https://stackoverflow.com/questions/61967112/round-up-current-time-to-next-30-mins-interval

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!