【问题标题】:Xcode time difference in days, hours, minutes and secondsXcode 天、时、分、秒的时差
【发布时间】:2015-01-01 14:01:22
【问题描述】:

首先:我想向所有阅读本文的人说新年快乐! 2015 年 5 月对我们所有人来说都是美好的一年:-)。

我正忙于制作一个计算两个日期之间时间差的函数。更准确地说:给定时间和日期与当前时间和日期之间的时间。 因此,用户选择过去的日期,然后程序在计时器中显示给定日期和今天日期之间的时间差,如下所示:“hh:mm:ss”

它可以正常运行并每秒更新我选择今天的时间(01-01-2015 10:00:00),但在过去的日期和时间时(31-12-2014 17:00 :00) 并将其与时间早于昨天 (01-01-2015 14:01:01) 的今天日期进行比较,它给了我一个负时间,就像倒数计时器一样:-2:-59:-59 .

但我希望它显示它的反面:21:01:01,如果可能的话,如果它超过 24:00:00,请指望。例如 25:12:39。

这是计算差值的代码:

    NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd-MM-YYYY HH:mm:ss"];
NSDate *date1 = [df dateFromString:[NSString stringWithFormat:@"30-12-2014 %@", startedTime]];
NSDate *date2 = [df dateFromString:[NSString stringWithFormat:@"31-12-2014 %@", [self getCurrentTime]]];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];

int hours = (int)interval / 3600;             // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
int seconds = (interval - (hours*3600) - (minutes*60)); // interval minus hours part (in seconds) divided by 60 yields minutes

NSString *timeDiff = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
_workingTime.text = [NSString stringWithFormat:@"%@",timeDiff];

有人可以帮忙吗?

【问题讨论】:

    标签: xcode date time timer difference


    【解决方案1】:
    [df setDateFormat:@"dd-MM-yyyy hh:mm:ss"];
    

    在格式字符串的这个改变之后尝试!

    这……终于。

    NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
    if( interval  < 0 ) {
      interval = [date1 timeIntervalSinceDate:date2];
    }
    

    More about date formats here

    【讨论】:

    • 你太棒了。不敢相信我没有看到。尤其是第一部分。谢谢它现在可以工作了!
    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 2021-07-15
    • 2015-02-03
    • 2020-11-25
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    相关资源
    最近更新 更多