I wanted to convert a date (nsdate) to tick values. Tick values are (1 Tick = 0.1 microseconds or 0.0001 milliseconds) since 1 Jan 0001 00:00:00 GMT. NSDate has functions like timeIntervalSince1970. So, how do I convert it?
Asked
Active
Viewed 2,613 times
4
-
For those who are looking for Swift methods to do this, see here: http://stackoverflow.com/a/41625877/253938 – RenniePet Jan 13 '17 at 01:16
1 Answers
3
I would like to share my experience:
I tried to find the seconds from 01/01/0001 and then multiply by 10,000,000. However, it gave me wrong results. So, I found out that 01/01/1970 is 621355968000000000 ticks from 01/01/0001 and used the following formula along with timeIntervalSince1970 function of NSDate.
Ticks = (MilliSeconds * 10000) + 621355968000000000
MilliSeconds = (Ticks - 621355968000000000) / 10000
Here is the outcome:
+(NSString *) dateToTicks:(NSDate *) date
{
NSString *conversionDateStr = [self dateToYYYYMMDDString:date];
NSDate *conversionDate = [self stringYYYYMMDDToDate:conversionDateStr];
NSLog(@"%@",[date description]);
NSLog(@"%@",[conversionDate description]);
double tickFactor = 10000000;
double timeSince1970 = [conversionDate timeIntervalSince1970];
double doubleValue = (timeSince1970 * tickFactor ) + 621355968000000000;
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setNumberStyle:NSNumberFormatterNoStyle];
NSNumber *nsNumber = [NSNumber numberWithDouble:doubleValue];
return [numberFormatter stringFromNumber:nsNumber];
}
Likewise, to convert from tick to date:
//MilliSeconds = (Ticks - 621355968000000000) / 10000
+(NSDate *) ticksToDate:(NSString *) ticks
{
double tickFactor = 10000000;
double ticksDoubleValue = [ticks doubleValue];
double seconds = ((ticksDoubleValue - 621355968000000000)/ tickFactor);
NSDate *returnDate = [NSDate dateWithTimeIntervalSince1970:seconds];
NSLog(@"%@",[returnDate description]);
return returnDate;
}

Topsakal
- 447
- 5
- 11
-
How are you accounting for leap years, leap seconds? Daylight savings in a time zone? – Abizern Sep 13 '12 at 16:37
-
1`double doubleValue = (timeSince1970 * tickFactor ) + 621355968000000000` is bad. You lose lots of precision by working with doubles. Better: `long long llValue = (long long)floor(timeSince1970 * tickFactor) + 621355968000000000LL; NSNumber *nsNumber = [NSNumber numberWithLongLong:llValue]`. The same is with conversion back. – Hrissan Jun 07 '13 at 10:55