NSDateIntervalFormatter prints dates even if dateStyle is set to NSDateFormatterNoStyle
I am using NSDateIntervalFormatter
to format a range of hours. They are always on the same day, so I don't want to show the date. In English speaking English, they would look like 21:00 - 22:00.
The problem occurs when the time crosses midnight. The end date is then technically the next day, and it NSDateIntervalFormatter
prints the date even if it's dateStyle
set to NSDateFormatterNoStyle
:
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.year = 2015;
comps.month = 5;
comps.day = 12;
comps.hour = 21;
NSDate *startDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
// next day, at midnight
comps.day = comps.day + 1;
comps.hour = 0;
NSDate *endDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
NSDateIntervalFormatter *formatter = [[NSDateIntervalFormatter alloc] init];
formatter.timeZone = [NSTimeZone localTimeZone];
formatter.dateStyle = NSDateFormatterNoStyle;
formatter.timeStyle = NSDateFormatterShortStyle;
NSString *string = [formatter stringFromDate:startDate toDate:endDate];
NSLog(@"%@", string);
// expected: 9:00 PM - 12:00 AM
// actual: 5/12/2015, 9:00 PM - 5/13/2015, 12:00 AM
Is there a way to get it to always hide the date without having to just format the two dates separately and join them with a dash?
source to share
If you remove Y / M / D from date components, it works as desired:
NSDateComponents *comps = [[NSDateComponents alloc] init];
// comps.year = 2015;
// comps.month = 5;
// comps.day = 12;
comps.hour = 21;
NSDate *startDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
// next day, at midnight
comps.day = comps.day + 1;
comps.hour = 24;
NSDate *endDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
NSDateIntervalFormatter *formatter = [[NSDateIntervalFormatter alloc] init];
formatter.timeZone = [NSTimeZone localTimeZone];
formatter.dateStyle = NSDateFormatterNoStyle;
formatter.timeStyle = NSDateFormatterShortStyle;
NSString *string = [formatter stringFromDate:startDate toDate:endDate];
// string = 9:00 PM - 12:00 AM
Also wondering if comps.day + 1 is removed, it shows:
1/3/1, 9:00 PM - 1/4/1, 12:00 AM
Which doesn't make sense to me ... 1/3 ?!
Update. It only seems to have the correct result when endDate is one day before startDate. This is not the case if it is more than a day off. This looks like undefined territory, doesn't work at will.
source to share