Date comparison

In NSDateTimeFormatter I have given GMT timeZone, But when doesRelativeDateFormatting is given as True, it compares with device timezone, instead I want to compare it with GMT time.

Replies

Is this question clear?

Can you give a code example of how you configured the formatter, plus: what input you gave it, and what output you got?

NSDate *inputDate = [NSDate date] ;

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *components = [calendar components: NSCalendarUnitYear| NSCalendarUnitMonth| NSCalendarUnitDay fromDate:inputDate];

[components setHour:0];

[components setMinute:0];

[components setSecond:0];

NSDate *newDate = [calendar dateFromComponents:components];

NSDateFormatter *dateFormat = [NSDateFormatter new];

[dateFormat setDateFormat:@"dd-MM-yyyy"];

dateFormat.doesRelativeDateFormatting = YES;

dateFormat.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];

[dateFormat stringFromDate:newDate];

Expected output: "Yesterday" because dateFormat timezone is "GMT"

Actual output: "Today" relative format calculated based on device time zone

Hope it clarifies.

Relative date formatting doesn't work at all for me if I use that code fragment on 10.13.3. (The results is an empty string.) However, it does seem to produce the correct results (for GMT, not local time) if I replace this line:


[dateFormat setDateFormat:@"dd-MM-yyyy"];


with these 2 lines:


dateFormatter.timeStyle = NSDateFormatterNoStyle;
dateFormatter.dateStyle = NSDateFormatterMediumStyle; // or Short or Long

What is the environment timezone that you have tested?

California. I used a date/time that was "Today" in London, but "Yesterday" in California, and got the correct word according to which time zone I set.