gpt4 book ai didi

ios - 如何计算给定日期后剩余的天,时,分和秒?

转载 作者:行者123 更新时间:2023-12-01 18:41:46 25 4
gpt4 key购买 nike

在我的应用程序中,我需要从JSON响应中获取给定日期的天,小时,分钟和秒。以下是我得到的日期和时间:

"date_time" = "2017-01-31 08:30:00";

并需要计算剩余天数:6小时:18分钟:24秒:30

结束日期将是今天的日期。我尝试了下面的代码,但它给了我很多天(我认为这需要UTC时区),并且还在SO上尝试了许多答案。
NSString *start = [[self.eventsArray valueForKey:@"date_time"]objectAtIndex:0];


NSDateFormatter *date = [[NSDateFormatter alloc] init];
[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *end = [date stringFromDate:[NSDate date]];


NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];


NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
fromDate:startDate
toDate:endDate
options:0];
NSLog(@"day : %ld H: %ld M : %ld S:%ld", [components day], (long)[components hour],(long)[components minute],(long)[components second]);

请有人帮我卡住。

最佳答案

您在这里输入错误,您的fromDate应该是今天的日期,即[NSDate date],而toDate将是您的startDate。因此,您的代码应该是这样的。

NSString *end = [[self.eventsArray valueForKey:@"date_time"]objectAtIndex:0];

NSDateFormatter *date = [[NSDateFormatter alloc] init];
[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//Start date
NSDate *startDate = [NSDate date];
NSDate *endDate = [f dateFromString:end];


NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond
fromDate:startDate
toDate:endDate
options:0];
NSLog(@"day : %ld H: %ld M : %ld S:%ld", [components day], (long)[components hour],(long)[components minute],(long)[components second]);

关于ios - 如何计算给定日期后剩余的天,时,分和秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41852126/

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