按日期查询 [英] PFQuery by date

查看:29
本文介绍了按日期查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PFQuery 搜索包含特定日期(无时间)的所有结果.我似乎无法弄清楚为什么它不起作用.我正在使用的代码如下.

I'm trying to search for all results that contain a certain date (no time) with a PFQuery. I can't seem to figure out why it is not working. My code I am using is below.

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"YYY-MM-dd"];
 NSString *today;
 today = [dateFormat stringFromDate:[NSDate date]];

 PFQuery *query = [PFQuery queryWithClassName:@"Booking"];

 [query whereKey:@"nextAppointment" equalTo:today];

 [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) { etc etc...

使用 Parse 网站将字段 nextAppointment 设置为日期.任何帮助将不胜感激

The field nextAppointment is set as a date using the Parse website. Any help would be appreciated

推荐答案

NSDate 对象和 Parse.com 日期字段都具有包含小时和分钟的精确时间.这意味着,如果您正在寻找发生在某一天的约会,您实际上是在搜索一个日期范围:该特定日期的上午 12:00 至晚上 11:59 的范围.

An NSDate object and the Parse.com Date field both have an exact time that includes hours and minutes. This means that if you are looking for an appointment that takes place on a certain day, you are actually searching a date range: the range from 12:00am until 11:59pm of that particular day.

如果您创建的 NSDate 没有明确的小时和分钟,Parse 不会知道您的意思是当天的所有日期"——它通过填充小时和分钟并搜索确切时间来解释它.您可以通过日期范围搜索来解决这个问题.

If you create an NSDate with no explicit hours and minutes, Parse doesn't know you mean "all dates on that day" - it interprets it by populating hours and minutes and searching for an exact time. You get around this with the date range search.

以下是如何从我的一个应用中执行此操作的示例,根据您的目的进行了修改:

Here is an example of how to do this from one of my apps, modified for your purposes:

//Create two dates for this morning at 12:00am and tonight at 11:59pm
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
[components setHour:0];
[components setMinute:0];
[components setSecond:1];
NSDate *morningStart = [calendar dateFromComponents:components];

[components setHour:23];
[components setMinute:59];
[components setSecond:59];
NSDate *tonightEnd = [calendar dateFromComponents:components];

PFQuery *query = [PFQuery queryWithClassName:@"Booking"];
[query whereKey:@"nextAppointment" greaterThan:morningStart];
[query whereKey:@"nextAppointment" lessThan:tonightEnd];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        //Etc...
    }
}];

这篇关于按日期查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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