如何在目标c中将秒转换为UnixtimeStamp?

时间:2016-12-15 16:17:43

标签: objective-c nsdate

 NSDate *now = [NSDate date];
    NSCalendar *calendar =  [NSCalendar currentCalendar];
    // find next date where the minutes are zero
    NSDate *nextHour = [calendar nextDateAfterDate:now matchingUnit:NSCalendarUnitMinute value:0 options:NSCalendarMatchNextTime];
    // get the number of seconds between now and next hour
    NSDateComponents *componentsToNextHour = [calendar components:NSCalendarUnitSecond fromDate:now toDate:nextHour options:0];
    //NSLog(@"%ld", componentsToNextHour.second);
    NSString *dec = [NSString stringWithFormat:@"%ld", (long)componentsToNextHour.second];

在上面的代码中,我将当前日期和时间转换为秒,但我无法将这些秒转换为unixtimestamp,任何有关如何进行此操作的想法都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

我不确定我理解你的问题。如果您要求下一个小时开始的Unix时间戳,请执行以下操作:

    NSDate *now = [NSDate date];
    NSCalendar *calendar =  [NSCalendar currentCalendar];
    // find next date where the minutes are zero
    NSDate *nextHour = [calendar nextDateAfterDate:now matchingUnit:NSCalendarUnitMinute value:0 options:NSCalendarMatchNextTime];
    time_t unixTimestampAtWhichNextHourStarts = (time_t)nextHour.timeIntervalSince1970;
    NSLog(@"ts=%ld", (long)unixTimestampAtWhichNextHourStarts);