以纪元显示当前时间

时间:2014-04-05 19:42:37

标签: ios iphone objective-c epoch

我正试图在时代中显示当前时间,我不确定这是否正确,但我确定不是因为它给了我一个错误:

NSDate *currentDate = [NSDate date];
NSDate *epochDate = [NSDate dateWithTimeIntervalSince1970:currentDate];

知道如何实现这个目标吗?

3 个答案:

答案 0 :(得分:1)

NSTimeInterval epoch = [[NSDate date] timeIntervalSince1970];
NSLog(@"%f", epoch);

或者更好的是,这只给出了时间的整数部分:

int epoch = round([[NSDate date] timeIntervalSince1970]);
NSLog(@"%d", epoch);

答案 1 :(得分:1)

NSString *epochTime = @"1347522689";
NSTimeInterval epochInterval = [epochTime longLongValue];
NSDate *epochNSDate = [[NSDate alloc] initWithTimeIntervalSince1970:epochInterval];
NSDateFormatter *dateFormatterEpoch = [[NSDateFormatter alloc] init];
[dateFormatterEpoch setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
NSString *epochDate = [dateFormatterEpoch stringFromDate:epochNSDate];

NSDate *currentDateNSDate = [NSDate date];
NSDateFormatter *dateFormatterCurrent = [[NSDateFormatter alloc] init];
[dateFormatterCurrent setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
NSString *currentDate = [dateFormatterCurrent stringFromDate:currentDateNSDate];


NSLog(@"epochDate = %@",epochDate);
NSLog(@"currentDate = %@", currentDate);

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

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags fromDate:epochNSDate toDate:currentDateNSDate options:0];

NSInteger year = [components month];
NSInteger months = [components month];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger min = [components minute];
NSInteger sec = [components second];


NSLog(@"Year Difference = %@\n Month Difference = %@\n, Days Difference = %@\n, Hours Difference = %@\n ,Minutes Difference = %@\n second Difference = %@\n", [[NSNumber numberWithInteger:year] stringValue] ,[[NSNumber numberWithInteger:months] stringValue], [[NSNumber numberWithInteger:days] stringValue], [[NSNumber numberWithInteger:hours] stringValue], [[NSNumber numberWithInteger:min] stringValue],[[NSNumber numberWithInteger:sec] stringValue]);

答案 2 :(得分:0)

将您的日期转换为纪元。您需要使用下面的dateWithTimeIntervalSince1970方法

NSDate *date = [NSDate date];
NSLog(@"epochDate: %f",([date timeIntervalSince1970]);