gpt4 book ai didi

iphone - 计算两个日期之间的差异的问题

转载 作者:行者123 更新时间:2023-11-28 22:46:56 25 4
gpt4 key购买 nike

我需要以分钟为单位计算两天之间的差异。

NSDate *now = [[NSDate alloc] init];

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[outputFormatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];

NSString* dateStringFromDatabase = @"01/01/1900 11:00:00 AM";

NSDate* dateFromString = [outputFormatter dateFromString:dateStringFromDatabase];

NSString* a = [outputFormatter stringFromDate:now];
NSDate* b = [outputFormatter dateFromString:a];

NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];

unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags fromDate:dateFromString
toDate:b options:0];

int hours = [components hour];
int minutes = [components minute];

self.lblResult.text = [NSString stringWithFormat:@"%i:%i", hours, minutes];

但是我有以下问题:对于当前时间,我得到:

2012-10-21 07:37:09 +0000 // wrong it's two hours late

当我尝试将 @"01/01/1900 11:00:00 AM" 转换为 NSDate 时,我得到了

1900-01-01 10:00:00 +0000 // also two hours late

最佳答案

试试这个......................

如果字符串中有日期,则使用 @"dd/MM/yyyy hh:mm:ss a"

将其转换为日期
NSDate *startDate = ...;
NSDate *endDate = ...;

现在日期比较

// Date Comparision
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];

unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags fromDate:LastDate
toDate:CuurentDate options:0];

获取两个日期之间的差异

int months = [components month];
int days = [components day];
int hours = [components hour];
int minutes = [components minute];

关于iphone - 计算两个日期之间的差异的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12974608/

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