iphone - 将 iphone 中当前日期的纪元时间转换为小时前、分钟前

标签 iphone nsdate nsdateformatter epoch

我的纪元时间是1347522689。现在我想显示从当前日期算起多少小时前、几分钟前的时间。我是这个领域的新手,请向我展示一些代码或任何建议,谢谢。

谢谢

最佳答案

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]);

关于iphone - 将 iphone 中当前日期的纪元时间转换为小时前、分钟前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12455223/

相关文章:

html - iOS tel:和mailto:链接仅适用于target =“_ blank”

ios - 如何从 NSDate 获得 1 小时的 future 时差

ios - setDefaultTimeZone 不起作用

objective-c - NSSortdescriptor 对从 NSManagedContext 获取结果无效

objective-c - 在 iPhone 中将多种日期格式转换为单一格式

ios - NSDateFormatter 在时间分析器中太慢

iphone - NSDateFormatter 模拟器上的日期不正确,设备上的日期正确

ios - 文字转语音不起作用?

iPhone OpenGl : importing 3D models

iphone - 自定义 UITableViewCell 不会在 setNeedsDisplay 上重绘