ios - NSDate dateWithTimeIntervalSince1970 添加额外的一天

标签 ios objective-c nsdate


我有一个方法可以更新标签并充当秒表。当我将字符串格式化为因素天数时,它工作得很好,并在其中添加了额外的一天。

例如。如果秒表在十分钟前启动,标签将显示:
01:00:10:00
它应该只显示

00:00:10:00

    - (void)updateTimer
{
    NSDate *currentDate = [NSDate date];
    NSDate *dateValue=[[NSUserDefaults standardUserDefaults] objectForKey:@"pickStart"];

    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:dateValue];

    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];

    // Create a date formatter
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd:HH:mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];

    // Format the elapsed time and set it to the label
    NSString *timeString = [dateFormatter stringFromDate:timerDate];
    self.stopWatchLabel.text = timeString;

}

任何帮助将不胜感激。

最佳答案

你所做的事情是不合适的。您的目标似乎是将 timeInterval 转换为天、小时、分钟和秒。您使用 timerDateNSDateFormatter 并不是实现该目标的正确方法。

timeInterval 不是距 1970 年 1 月 1 日的偏移量,并且 timeInterval 不代表日期。

您应该做的是获取 currentDatedateValue 之间的差异作为一组 NSDateComponents

- (void)updateTimer {
    NSDate *currentDate = [NSDate date];
    NSDate *dateValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"pickStart"];

    unsigned int unitFlags = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *comps = [[NSCalendar currentCalendar] components:unitFlags fromDate:dateValue  toDate:currentDate  options:0];
    int days = [comps day];
    int hours = [comps hours];
    int minutes = [comps minutes];
    int seconds = [comps seconds];

    NSString *timeString = [NSString stringWithFormat:@"%d:%02d:%02d:%02d", days, hours, minutes, seconds];
    self.stopWatchLabel.text = timeString;
}

关于ios - NSDate dateWithTimeIntervalSince1970 添加额外的一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37010014/

相关文章:

ios - NSBundles 中的类

ios - 如何对包含日期对象的自定义数组进行排序

iphone - 当时间为 24 小时格式时,来自 NSString 的 NSDate

iOS:警告 "attempt to present ViewController whose view is not in the window hierarchy"

iphone - 如何使用矩形裁剪图像?

ios - 为什么 View 的边距必须为 -20 才能使其接近屏幕末尾,为什么不为零?

objective-c - OCMock - 试图模拟 NSEntityDescription

objective-c - 适用于 iOS 的 Luma Key(从图像创建 alpha 蒙版)

ios - CFBundleDisplayName 返回 'null'

ios - 根据值嵌套 NSDictionary