3

我想在 ios 中将时间小时分钟秒转换为秒。有没有内置的方法呢?我怎样才能做到这一点?

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *componentsDiff = [gregorianCalendar components:NSHourCalendarUnit fromDate:[NSDate date]];
4

3 回答 3

3

以下代码将日期作为字符串插入,然后返回秒数。

- (NSNumber *)dateToSecondConvert:(NSString *)string {

    NSArray *components = [string componentsSeparatedByString:@":"];

    NSInteger hours   = [[components objectAtIndex:0] integerValue];
    NSInteger minutes = [[components objectAtIndex:1] integerValue];
    NSInteger seconds = [[components objectAtIndex:2] integerValue];

    return [NSNumber numberWithInteger:(hours * 60 * 60) + (minutes * 60) + seconds];
}

愿这对很多人有帮助。

于 2012-12-14T13:29:53.387 回答
2

也许我误解了这个问题,但这将为您提供 1970 年以来的当前时间(以秒为单位)

[[NSDate date] timeIntervalSince1970]
于 2012-12-14T13:35:43.443 回答
1

很多例子,但这是你可以做的:

NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [calendar components:NSHourCalendarUnit fromDate:now];
//[comp hour]
//[comp minute]
//[comp second]
于 2012-12-14T13:14:48.027 回答