Ios 使用相对数据格式设置日期格式
我的目标:如果当前日期是今天或昨天,请使用“今天”和“昨天”这两个词。如果当前日期早于今天或昨天,则使用以下格式:8月15日星期四。当我将setDoesRelativeDateFormatting设置为NO时,我可以使用@EEE,MMM d实现此格式,但是当我尝试使用以下代码时,它会崩溃并显示2013年8月12日,这不是我想要的Ios 使用相对数据格式设置日期格式,ios,objective-c,nsdate,Ios,Objective C,Nsdate,我的目标:如果当前日期是今天或昨天,请使用“今天”和“昨天”这两个词。如果当前日期早于今天或昨天,则使用以下格式:8月15日星期四。当我将setDoesRelativeDateFormatting设置为NO时,我可以使用@EEE,MMM d实现此格式,但是当我尝试使用以下代码时,它会崩溃并显示2013年8月12日,这不是我想要的 // Set up the date formatter NSDateFormatter *dateFormatter = [[NSDateFormat
// Set up the date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
dateFormatter.dateFormat = @"EEE, MMM d";
[dateFormatter setDoesRelativeDateFormatting:YES];
[dateFormatter setLocale:[NSLocale currentLocale]];
这是一个黑客,因为我无法找到一个内置的方式来执行这项任务,但它的工作几乎完美无瑕。唯一的问题是它输出的是月份的全名,而不是一个简短的输出。当然,如果需要的话,可以用类似于我在下面代码中对这一年所做的方式来修复
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateStyle:NSDateFormatterFullStyle];
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSYearCalendarUnit fromDate:[NSDate date]];
NSString *theYear = [NSString stringWithFormat:@", %ld", comps.year];
[dateFormatter setDoesRelativeDateFormatting:YES];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
if ([dateString isEqualToString:@"Today"] || [dateString isEqualToString:@"Yesterday"]) {
NSLog(@"%@", dateString);
} else {
dateString = [dateString stringByReplacingOccurrencesOfString:theYear withString:@""];
NSLog(@"%@", dateString);
}
当相对格式在今天打印时,当它在8月16日星期五打印时,有一点警告:此解决方案不能很好地处理本地化设备。这是正确的,如果更改区域设置,它将中断。您可以在不使用逗号的情况下更改年份字符串,这将允许您删除任何区域设置中的年份。不幸的是,viernes,16 de agosto de不是用西班牙语输出日期的正确方法。关于relativeDateFormat的文档在主题上非常清楚::我不确定@RobvanderVeer的内容如果relativeDateFormat设置为YES,那么它在所有地区都能工作。如果不是,格式将显示为我在上面为西班牙语16 de agosto Destry复制的格式,可能我对这个问题理解不够。检查这里: