我正在尝试创建一个函数来提取仅具有特定日期时间戳的数据。它适用于一个项目,该集合中的最新数据来自二月份。我还是想用昨天的标准,上周,上个月的参数。
有没有办法将“当前日期”设置为特定日期,以便我可以根据该时间而不是实际当前日期制作时间范围?
这就是我试过的
NSString *datestr = @"2014-02-16T04:59:50.021Z";
NSDateFormatter *dformat = [[NSDateFormatter alloc]init];
[dformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];
NSDate *date = [dformat dateFromString:datestr];
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *yesterday = [[NSDate date] dateByAddingTimeInterval: date -secondsPerDay];
NSDate *lastWeek = [[NSDate alloc]initWithTimeIntervalSinceNow: - secondsPerDay * 7];
NSDate *lastMonth = [[NSDate alloc]initWithTimeIntervalSinceNow:-secondsPerDay * 30];
尝试从secondsPerDay
中减去date
会产生算术错误。任何解决方法?
答案 0 :(得分:1)
您无法从NSTimeInterval
(对象)中减去double
(NSDate
)。您希望将dateByAddingTimeInterval:
消息发送到减去时间的日期:
NSString *datestr = @"2014-02-16T04:59:50.021Z";
NSDateFormatter *dformat = [[NSDateFormatter alloc]init];
[dformat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssz"];
NSDate *date = [dformat dateFromString:datestr];
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *yesterday = [date dateByAddingTimeInterval:-secondsPerDay];
NSDate *lastWeek = [date dateByAddingTimeInterval:-(secondsPerDay * 7)];
NSDate *lastMonth = [date dateByAddingTimeInterval:-(secondsPerDay * 30)];
但请注意,lastMonth
不完全正确,因为并非每个月都有30天。相反,您可能还想查看NSDateComponents
:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *todayComponents = [NSDateComponents new];
todayComponents.year = 2014;
todayComponents.month = 2;
todayComponents.day = 16;
todayComponents.hour = 4;
todayComponents.minute = 59;
todayComponents.second = 50;
NSDate *today = [calendar dateFromComponents:todayComponents];
NSDateComponents *offset = [NSDateComponents new];
offset.day = -1;
NSDate *yesterday = [calendar dateByAddingComponents:offset toDate:today options:0];
offset = [NSDateComponents new];
offset.day = -7;
NSDate *lastWeek = [calendar dateByAddingComponents:offset toDate:today options:0];
offset = [NSDateComponents new];
offset.month = -1;
NSDate *lastMonth = [calendar dateByAddingComponents:offset toDate:today options:0];