How to get the current hour using Cocoa?

How to get the current hour in Cocoa using Objective-C?

+3
source share
5 answers

To get started, you should read Themes on dates and programming times for Cocoa . This will give you a good idea of ​​using the various date / time / calendar objects that Cocoa provides for high-level date conversions.

This snapshot of code, however, will answer your specific problem:

- (NSInteger)currentHour
{
    // In practice, these calls can be combined
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];

    return [components hour];
}
+38
source

One way is to use NSCalendar and NSDateComponents

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
NSInteger hour = [components hour];
+6
source

Cocoa, , . , , , ​​ NSDateComponents. :

// Function Declaration (*.h file)
-(NSDateComponents *)getCurrentDateTime:(NSDate *)date;

// Implementation
-(NSDateComponents *)getCurrentDateTime:(NSDate *)date
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components:NSHourCalendarUnit + NSMinuteCalendarUnit + NSSecondCalendarUnit fromDate:now];
    return comps;

}

// call and usage

NSDateComponents *today = [self getCurrentDateTime:[NSDate date]];
        hour = [today hour];
        minute = [today minute];
        second = [today second];

, NSCalendar - enum, '+'

, , .

+2
[NSDate date]

, . , , , ? ?

+1

func currentHour() -> Int {
    let now = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.Hour, fromDate: now)

    return components.hour
}
0

Source: https://habr.com/ru/post/1706316/


All Articles