Title here
Summary here
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Objective-C.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Use NSDate and timeIntervalSince1970 to get elapsed time since the Unix epoch in seconds
NSDate *now = [NSDate date];
NSLog(@"%@", now);
// Get seconds since epoch
NSTimeInterval secondsSinceEpoch = [now timeIntervalSince1970];
NSLog(@"%.0f", secondsSinceEpoch);
// Get milliseconds since epoch
long long millisecondsSinceEpoch = (long long)(secondsSinceEpoch * 1000.0);
NSLog(@"%lld", millisecondsSinceEpoch);
// Get nanoseconds since epoch
long long nanosecondsSinceEpoch = (long long)(secondsSinceEpoch * 1000000000.0);
NSLog(@"%lld", nanosecondsSinceEpoch);
// You can also convert integer seconds or nanoseconds since the epoch into the corresponding NSDate
NSDate *dateFromSeconds = [NSDate dateWithTimeIntervalSince1970:secondsSinceEpoch];
NSLog(@"%@", dateFromSeconds);
NSDate *dateFromNanoseconds = [NSDate dateWithTimeIntervalSince1970:((double)nanosecondsSinceEpoch / 1000000000.0)];
NSLog(@"%@", dateFromNanoseconds);
}
return 0;
}
To run the program, save it as Epoch.m
and compile it with:
$ clang -framework Foundation Epoch.m -o epoch
$ ./epoch
2023-05-18 12:34:56 +0000
1684413296
1684413296000
1684413296000000000
2023-05-18 12:34:56 +0000
2023-05-18 12:34:56 +0000
In Objective-C, we use NSDate
to work with dates and times. The timeIntervalSince1970
method gives us the number of seconds since the Unix epoch. We can then convert this to milliseconds or nanoseconds by multiplying.
To create an NSDate
from seconds or nanoseconds since the epoch, we use the dateWithTimeIntervalSince1970:
class method.
Next, we’ll look at another time-related task: time parsing and formatting.