gpt4 book ai didi

ios - 两个nsdates之间的时间差

转载 作者:行者123 更新时间:2023-11-29 10:50:51 25 4
gpt4 key购买 nike

我的目标是制作一个倒计时标签。因此,例如,我想显示时间 19:00:00 与当前时间之间的时差。我在下面为它写了一个代码。另外,我已经使用 sqlite 存储了一个时间; 19:00:00。

    //start time
NSString *starttime = mission.starttime;
NSDate *starttime_convert;
NSDateFormatter *formatttter = [[NSDateFormatter alloc]init];
[formatttter setDateFormat:@"HH:mm:ss"];
starttime_convert = [formatttter dateFromString:starttime];

//current time
NSDate *nowtime = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone systemTimeZone] secondsFromGMT]];
//NSLog(@"Current Time %@", nowtime);

float countdown = [nowtime timeIntervalSinceDate:starttime_convert];
int hh = (countdown/3600);
NSLog(@"%d",hh);
int mm = ((countdown-(hh*3600))/60);
int ss = countdown-(hh*3600+mm*60);
NSLog(@"%02d:%02d:%02d",hh,mm,ss);

但是,显示的结果是 122238:43:32。因为,当前时间是 16:44:32,它应该显示 02:15:68。但事实并非如此。

谁能帮我解决这个问题?

最佳答案

您应该在开始时间中指定当前日期,而不仅仅是 @"19:00:00"

为此,您可以使用以下代码:

NSString *starttime = @"19:00:00";
NSArray *times = [starttime componentsSeparatedByString:@":"];

int hour = [times[0] integerValue];
int minute = [times[1] integerValue];
int second = [times[2] integerValue];

NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: hour];
[components setMinute: minute];
[components setSecond: second];

NSDate *starttime_convert = [gregorian dateFromComponents: components];

//current time
//NSDate *nowtime = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone systemTimeZone] secondsFromGMT]];
float countdown = -[date timeIntervalSinceDate:starttime_convert];//pay attention here.
int hh = (countdown/3600);
NSLog(@"%d",hh);
int mm = ((countdown-(hh*3600))/60);
int ss = countdown-(hh*3600+mm*60);
NSLog(@"%02d:%02d:%02d",hh,mm,ss);

关于ios - 两个nsdates之间的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20513369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com