Time in Objective-C
Our first example demonstrates how to work with times and durations in Objective-C. Here’s the full source code:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"%@", [NSDate date]);
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2009];
[components setMonth:11];
[components setDay:17];
[components setHour:20];
[components setMinute:34];
[components setSecond:58];
[components setNanosecond:651387237];
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *then = [calendar dateFromComponents:components];
NSLog(@"%@", then);
NSLog(@"%ld", (long)[components year]);
NSLog(@"%ld", (long)[components month]);
NSLog(@"%ld", (long)[components day]);
NSLog(@"%ld", (long)[components hour]);
NSLog(@"%ld", (long)[components minute]);
NSLog(@"%ld", (long)[components second]);
NSLog(@"%ld", (long)[components nanosecond]);
NSLog(@"%@", [calendar timeZone]);
NSDateComponents *weekdayComponents = [calendar components:NSCalendarUnitWeekday fromDate:then];
NSLog(@"%ld", (long)[weekdayComponents weekday]);
NSDate *now = [NSDate date];
NSLog(@"%d", [then compare:now] == NSOrderedAscending);
NSLog(@"%d", [then compare:now] == NSOrderedDescending);
NSLog(@"%d", [then compare:now] == NSOrderedSame);
NSTimeInterval diff = [now timeIntervalSinceDate:then];
NSLog(@"%f", diff);
NSLog(@"%f", diff / 3600);
NSLog(@"%f", diff / 60);
NSLog(@"%f", diff);
NSLog(@"%f", diff * 1000000000);
NSLog(@"%@", [then dateByAddingTimeInterval:diff]);
NSLog(@"%@", [then dateByAddingTimeInterval:-diff]);
}
return 0;
}
Let’s break down the key points:
We start by getting the current time using
[NSDate date]
.We create a specific date using
NSDateComponents
andNSCalendar
. This is equivalent to thetime.Date()
function in Go.We can extract various components of the date using the
NSDateComponents
properties.The weekday can be obtained using the
NSCalendarUnitWeekday
component.We can compare dates using the
compare:
method, which returns anNSComparisonResult
.To get the duration between two dates, we use
timeIntervalSinceDate:
, which returns a number of seconds as anNSTimeInterval
.We can perform various calculations with this interval, such as converting to hours, minutes, etc.
Finally, we can add or subtract time intervals from dates using
dateByAddingTimeInterval:
.
To run this program, save it as TimeExample.m
and compile it with:
$ clang -framework Foundation TimeExample.m -o TimeExample
Then run it with:
$ ./TimeExample
This will output the current time, the specified time, and various calculations and comparisons between them.
Note that Objective-C uses the NSDate
class and related Foundation framework classes for date and time operations, which offer similar functionality to Go’s time
package, but with a different API.