NSTimeInterval在给定月份的最后一天似乎不正确-iOS [英] NSTimeInterval seems to be wrong for last day of the given month- iOS

查看:60
本文介绍了NSTimeInterval在给定月份的最后一天似乎不正确-iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的本地数据库中,我保存了一个NSTimeInterval值列表.我必须找出并获取给定月份中所有可用的记录.唯一的问题是无法获取给定月份的最后一天的记录.

In my local database, I have a list of NSTimeInterval values saved. I have to find out and fetch all records available in a given Month. The only problem is in fetching records for last day of the given month seems to be unavailable.

可以说给定的月份是12月,所以我必须提取12月1日至12月31日(直到11:59 PM)的所有记录

Lets say given month is December so I have to fetch all the records from 1st Dec to 31st Dec (Till 11:59PM)

我正在使用以下实现:

[self.dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *startDate = [self.dateFormatter dateFromString:@"1-12-2012"];
NSDate *endDate = [self.dateFormatter dateFromString:@"31-12-2012"];

NSTimeInterval startDateTimeInterval = [startDate timeIntervalSince1970];
NSTimeInterval endDateTimeInterval = [endDate timeIntervalSince1970];

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"(mdate >= %f) AND (mdate <= %f)",startDateTimeInterval,endDateTimeInterval]];

我注意到 endDateTimeInterval 的double值与数据库在31日(上午9点)保存的值相比要小得多.但是,怎么可能呢,我希望我的endDateTime应该到12月31日晚上11:59为止.

I have noticed that endDateTimeInterval double value is pretty less as compared to saved value in the database for 31st (9AM). But howz it possible, I am expecting my endDateTime should be till 31st Dec 11:59 PM.

请提供有关此问题的意见.

Please provide your inputs on this issue.

推荐答案

您正在隐式创建的 NSDate 对象的时间为00:00.因此,谓词搜索将不包括从时间00:01到23:59的最后一天.最简单的更改是将结束日期设置为第二天(下个月的第一天),并将谓词更改为小于,而不是小于或等于.

The NSDate objects you are creating implicitly have a time of 00:00. So the predicate search will not include the last day from time 00:01 to 23:59. The easiest change is to set the end date to the next day (first of next month) and change the predicate to a less than, instead of less than or equal.

[self.dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *startDate = [self.dateFormatter dateFromString:@"1-12-2012"]; // start of range, inclusive
NSDate *endDate = [self.dateFormatter dateFromString:@"1-1-2013"]; // end of range, exclusive
...        
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"(mdate >= %f) AND (mdate < %f)",startDateTimeInterval,endDateTimeInterval]];

这篇关于NSTimeInterval在给定月份的最后一天似乎不正确-iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆