PFQuery按日期 [英] PFQuery by date

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

问题描述

我正在尝试使用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...
    }
}];

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

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