【发布时间】:2015-07-27 17:12:07
【问题描述】:
我有两个通过按钮设置的日期。这些存储在一个继承自 NSObject 的自定义对象中。
属性:
@property (nonatomic, strong) NSDate *firstDate;
@property (nonatomic, strong) NSDate *secondDate;
自定义 getter 和 setter 方法:
- (void)setFirstDate:(float)firstDate {
_firstDate = [self dateByOmittingSeconds:firstDate];
}
- (void)setSecondDate:(float)secondDate {
_secondDate = [self dateByOmittingSeconds:secondDate];
}
- (NSDate *)firstDate {
return [self dateByOmittingSeconds:_firstDate];
}
- (NSDate *)secondDate {
return [self dateByOmittingSeconds:_secondDate];
}
删除 NSDate 秒部分的函数:
-(NSDate *)dateByOmittingSeconds:(NSDate *)date
{
// Setup an NSCalendar
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
// Setup NSDateComponents
NSDateComponents *components = [gregorianCalendar components: NSUIntegerMax fromDate: date];
// Set the seconds
[components setSecond:00];
return [gregorianCalendar dateFromComponents: components];
}
firstDate 是 08:00,secondDate 是 13:00,两者都是今天设置的。
我正在获取两个日期之间的距离并将它们格式化如下:
NSString *myString = [self timeFormatted:[currentModel.secondDate timeIntervalSinceDate:currentModel.firstDate]];
- (NSString *)timeFormatted:(int)totalSeconds
{
// int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return [NSString stringWithFormat:@"%luh %lum", (unsigned long)hours, (unsigned long)minutes];
}
但它报告 4h 59m,17999.254732 秒。
有人知道这是为什么吗?
谢谢!
【问题讨论】:
标签: ios objective-c nsdate nstimeinterval