NSLog showing the previous Date

青春壹個敷衍的年華 提交于 2019-12-02 06:30:59

问题


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


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!