2012-09-13 58 views
4

我想将日期(nsdate)转换为刻度值。自1月1日00:00:00 GMT以来,Tick值为(1 Tick = 0.1微秒或0.0001毫秒)。 NSDate的功能类似于timeIntervalSince1970。那么,我该如何转换它?NSDate to Tick转换

+0

对于那些正在寻找Swift方法来做到这一点,请看这里:htt p://stackoverflow.com/a/41625877/253938 – RenniePet

回答

3

我想和大家分享我的经验:

我试图从01/01/0001找到秒钟,然后乘以10,000,000。但是,它给了我错误的结果。因此,我发现01/01/1970是01/01/0001中的621355968000000000个刻度,并使用以下公式与NSDate的timeIntervalSince1970函数一起使用。

蜱=(毫秒* 10000)+ 621355968000000000

毫秒=(蜱 - 621355968000000000)/ 10000

下面是结果:

+(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]; 
} 

同样地,为了从蜱转换到日期:

//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; 
} 
+0

你是如何考虑闰年,闰秒?夏时制在一个时区? – Abizern

+1

'double doubleValue =(timeSince1970 * tickFactor)+ 621355968000000000' is bad。与双打一起工作会让你失去很多精确度。更好的是:'long long llValue =(long long)floor(timeSince1970 * tickFactor)+ 621355968000000000LL; NSNumber * nsNumber = [NSNumber numberWithLongLong:llValue]'。 转换回来也是一样。 – Hrissan