我使用NSDateIntervalFormatter
格式化一系列小时数。他们总是在同一天,所以我不想显示日期。在美国英语区域,它们看起来像晚上9点到晚上10点。
当时间跨越午夜时出现问题。然后,结束日期在技术上在第二天,NSDateIntervalFormatter
打印日期,即使其dateStyle
设置为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
有没有办法让它始终隐藏日期,而不必单独格式化两个日期并用破折号加入它们?
答案 0 :(得分:2)
If you eliminate the Y/M/D from the date components it works as desired:
@"string"
Also interesting is if comps.day + 1 is removed, it shows:
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
Which to me makes no sense.... 1/3?!
Update: It appears to be have the correct result only when endDate is one day before startDate. It does not if it's more than a day off. This feels like undefined territory, not working as desired.