NSDate and currentTimeMillis

Published on — Filed under protip, cocoade

Been coding in Objective-C?

Miss Java's System.currentTimeMillis()?

Well, look no further!

@interface NSDate (BBExtensions)

+ (long long)currentTimeMillis;
+ (NSDate *)dateFromMillis:(long long)millis;

@end

... and the implementation:

#import "NSDate+BBExtensions.h"

#import <sys/time.h>

@implementation NSDate (BBExtensions)

+ (long long)currentTimeMillis {
  struct timeval t;
  gettimeofday(&t, NULL);

  return (((long long) t.tv_sec) * 1000) + (((long long) t.tv_usec) / 1000);
}

+ (NSDate *)dateFromMillis:(long long)millis {
   return [NSDate dateWithTimeIntervalSince1970:(millis / 1000)];
}

@end

Tested, approved & certified to work on AppKit and UIKit.