【问题标题】:iOS: problem with NSDate and NSDateComponentiOS:NSDate 和 NSDateComponent 的问题
【发布时间】:2011-08-23 22:57:44
【问题描述】:
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setTimeZone:[ NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ] ;
[components setYear:2011];
[components setDay:13];
[components setMonth:5];
NSDate *date1 = [gregorianCalendar dateFromComponents:components];
NSDate *date2 = [[NSDate alloc] init];


    NSTimeInterval diff = [data2 timeIntervalSinceDate:date1];
    NSString *intervalString = [NSString stringWithFormat:@"%f", diff];
    int second = [intervalString intValue];
    int period = second/3600/24; 
    NSLog(@"period:%d", period);
    NSLog(@"date1:%@", data1);
    NSLog(@"date2:%@", data2);

consol 中的结果是:

2011-05-12 10:57:00.406 项目[297:707] 周期:0;

2011-05-12 10:57:00.375 项目[297:707] data2:2011-05-12 08:56:52 +0000

2011-05-12 10:57:00.402 项目[297:707] data1:2011-05-13 00:00:00 +0000

我不明白为什么句号是“0”,它必须是“1”;你能帮帮我吗?

【问题讨论】:

    标签: objective-c xcode nsdate nsdatecomponents nstimeinterval


    【解决方案1】:

    NSTimeInterval 只是一个双精度数,因此您不需要将其转换为字符串然后再转换回 int。

    如果你这样做会发生什么:

    NSTimeInterval diff = [data2 timeIntervalSinceDate:date1];
    int period = (int)diff/3600/24; 
    NSLog(@"period:%d", period);
    

    另外,如果间隔是 diff 小于 3600*24,则 diff/3600/24 的结果将小于 1,因此 int 值将被展平为 0。

    【讨论】:

    • 那么我必须使用一个指令,每个时间段(双精度)在点之后添加一个值。例如,如果我有 1,01,它必须是 2,或者如果我有 4,67,它必须是 5....对吗?
    • 把周期变成双倍怎么样?这样您就不会失去任何精度。
    【解决方案2】:

    date2 是 当前 日期。不知道为什么period 应该在这里。

    在撰写本文时,差异约为。 -53000。将其除以您得到的结果和预期的结果为零。

    还请记住,NSTimeInterval 是一个浮点数,您通过字符串将其转换为整数,这将丢弃分数。

    没有意义通过字符串进行这种转换 - 只需使用 int seconds = (int) diff;

    直接复制/粘贴您的代码,因为您引用了data1data2,但您的变量称为date1date2。但是,如果这些变量在其他地方声明,这可能已经是你的错误了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-14
      相关资源
      最近更新 更多