Search code examples
iosswift2nsdatehour

Swift 2.3 Nearest Hour (Superior or Equal) from current Date


I have to determine H and H+3 where H is >= to nearest Hour.

Let me show you some examples :

if today's hour is 0h00 -> H = 0h and H+3 = 3h

if today's hour is 0h01 -> H = 1h and H+3 = 3h

if today's hour is 21h00 -> H = 21h and H+3 = 0h

if today's hour is 22h34 -> H = 23h and H+3 = 2h (day + 1)

I am new to Swift, I know how to get the nearest hour in Obj C, but with Swift I'm not sure.

Is there a fast way to determine those 2 variables H and H+3 in order to set the text of two labels at any given time.

I tried this method but it gives me the nearest hour but the closest one, not >=.

func nextHourDate() -> NSDate? {
    let calendar = NSCalendar.currentCalendar()
    let date = NSDate()
    let minuteComponent = calendar.components(NSCalendarUnit.Minute, fromDate: date)
    let components = NSDateComponents()
    components.minute = 60 - minuteComponent.minute
    return calendar.dateByAddingComponents(components, toDate: date, options: [])
}

I'm developing in Swift 2.3

EDIT :

After reading the answers/comments, here is what I developed.

func determineH() -> NSDate? {
        let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        let now = NSDate()
        let components = gregorian.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: now)

        if components.minute != 0 {
            components.hour = components.hour + 1
            components.minute = 0
        }

        let date = gregorian.dateFromComponents(components)!
        return date
    }

Solution

  • based on your code:

    check minutes of the current hour and go back to the last full hour and only then add!?

    Ill not provide the code for that arithmetic masterpiece since you already almost there

    best: work with dateComponents more

    only increase the hours property and reset minutes to 0!?

    comps.hours += 1
    comps.minutes = 0