I want to retrieve all the entries from core data added between two dates.I am using NSPredicate
. As I am not getting the correct result I tried logging the date.It is showing the previous dates.After googling for a while I added
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
to my code.Now,Its showing correct dates but the results are still wrong.
This is the code I used.
NSDate *fromDate = [[self dateFormatter]dateFromString:self.fromDateField.text];
NSLog(@"%@",fromDate);
NSDate *toDate = [[self dateFormatter]dateFromString:self.toDateField.text];
NSLog(@"%@",toDate);
NSComparisonResult result = [fromDate compare:toDate];
switch (result) {
case NSOrderedAscending:
{
//code
}
- (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
}
return dateFormatter;
}
Thanks in advance
If you log an NSDate object directly it will always display the tome in GMT/UTC timezone. you have to log the output of a date formatter.
NSLog(@"%@",[self.dateFormatter stringFromDate:toDate]);
This will take your timezone in account. Or better: the timezone of the dateformatter's calendar — what is the device default if you dont change that.
来源:https://stackoverflow.com/questions/16080095/nslog-showing-the-previous-date