显示当前时间

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

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

任何想法如何做到这一点?

 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]); 
 NSTimeInterval epoch = [[NSDate date] timeIntervalSince1970]; NSLog(@"%f", epoch); 

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

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

将你的date转换为纪元。 你需要使用如下所示的dateWithTimeIntervalSince1970方法

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