Date+MinutesFromMidnight.swift 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import Foundation
  2. enum MinutesFromMidnightError: LocalizedError, Equatable {
  3. case invalidCalendar
  4. var errorDescription: String? {
  5. switch self {
  6. case .invalidCalendar:
  7. return "Unable to extract hours and minutes from the current calendar"
  8. }
  9. }
  10. }
  11. extension Date {
  12. /// Returns the total minutes elapsed since midnight for the current date
  13. private var minutesSinceMidnight: Int? {
  14. let calendar = Calendar.current
  15. let components = calendar.dateComponents([.hour, .minute], from: self)
  16. guard let hour = components.hour, let minute = components.minute else {
  17. return nil
  18. }
  19. return hour * 60 + minute
  20. }
  21. /// Checks if the current time falls within the specified range of minutes
  22. /// - Parameters:
  23. /// - lowerBound: The lower bound in minutes since midnight (inclusive)
  24. /// - upperBound: The upper bound in minutes since midnight (exclusive)
  25. /// - Returns: Boolean indicating if the current time is within the specified range
  26. func isMinutesFromMidnightWithinRange(lowerBound: Int, upperBound: Int) throws -> Bool {
  27. guard let currentMinutes = minutesSinceMidnight else {
  28. throw MinutesFromMidnightError.invalidCalendar
  29. }
  30. return currentMinutes >= lowerBound && currentMinutes < upperBound
  31. }
  32. }