I had to recently process a Ticks value from an ASP.net website in a macOS app. None of the solutions I would around the web worked so here are some quick examples of how to get the tick value from a NSDate and get an NSDate from a tick value.
NSDate to ticks
NSDate *inputDate = [NSDate date]; // Get time in seconds since 1970. // Then add the amount of seconds from year 1 to 1970. double diff = [inputDate timeIntervalSince1970]; diff += 62135596800; // 1 tick is 100 nanoseconds. Convert to that. long long int ticks = llround(diff * 10000000);
The number 62135596800 was an estimate followed by a few adjustments. The result of the code above matches up with .NET in my tests.
Ticks to NSDate
double since1970 = (ticks / 10000000.00) - 62135596800; NSDate *date = [NSDate dateWithTimeIntervalSince1970:since1970];
Both ticks and NSDate are UTC based.
I've seen other attempts to calculate ticks by create a NSDate with January 1st in year 1 and then taking the difference from that. But NSDate doesn't seem to handle dates that old.
I tried using an NSDateFormatter like this:
NSDateFormatter *f = [[NSDateFormatter alloc] init]; [f setDateFormat:@"y-M-d"]; NSDate *date = [f dateFromString:@"0001-01-01"];
But that will give a date that is around 30th of december year 0. I say around because it seems to give different results depending on when it is run. It never matches january 1st.
There's a similar thing with using
[NSDate dateWithTimeIntervalSince1970:-62135596800]. It is closer than the NSDateFormatter code but will random be a number of minutes off.
I'm not sure if this is a bug or just a limitation of NSDate. It might require the use of NSCalendar to get the correct date.