在设置doesRelativeDateFormatting = YES时,stringFromDate返回nil

Ayu*_*oel 12 iphone nsdateformatter ios

在NSDateFormatter文档中,

如果日期格式化程序使用相对日期格式,则在可能的情况下,它会使用短语(例如"今天"或"明天")替换其输出的日期组件 - 表示相对日期.

我使用以下代码:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEEE dMMMM',' hma"
                                                       options:0
                                                        locale:[NSLocale currentLocale]];
formatter.doesRelativeDateFormatting = YES;
NSLog(@"Date: %@", [formatter stringFromDate:[NSDate date]]);
Run Code Online (Sandbox Code Playgroud)

它记录Date:.

但在评论formatter.doesRelativeDateFormatting = YES;输出结果是正确的.

Date: Tuesday, 19 August 1:18 pm

我理解doesRelativeDateFormatting错了吗?

Sre*_*att 6

嗨,当我修改这样的代码.有用..

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
 formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEEE dMMMM',' hma"
                                                       options:0
                                                        locale:[NSLocale currentLocale]];
 [formatter setDateStyle:NSDateFormatterFullStyle];
 [formatter setTimeStyle:NSDateFormatterShortStyle];
 formatter.doesRelativeDateFormatting = YES;
  NSLog(@"Date: %@", [formatter stringFromDate:[NSDate date]]);
Run Code Online (Sandbox Code Playgroud)


Smo*_*ngo 5

它似乎doesRelativeDateFormatting不适用于自定义dateFormat.

我有同样的挑战,你要显示Today, 11:44 pm19 Aug, 1:23 am.困难的部分是,这一年总是被排除在外.

我这样解决了:

获取您喜欢的任何样式的格式化日期,并doesRelativeDateFormatting启用

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.doesRelativeDateFormatting = true
var dateString = dateFormatter.stringFromDate(dateToFormat)
Run Code Online (Sandbox Code Playgroud)

从同一日期获取格式化的年份(确保dateFormat具有正确的y代表年份.我使用4 y,因为中日期样式使用全年格式.

let yearFormatter = NSDateFormatter()
yearFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("yyyy", options: 0, locale: NSLocale.currentLocale())
let yearString = dateFormatter.stringFromDate(dateToFormat)
Run Code Online (Sandbox Code Playgroud)

最后通过从生成中删除年份dateString并修剪一些多余的空白来构成最终字符串.

var finalString = dateString.stringByReplacingOccurrencesOfString(yearString, withString: "")
finalString = finalString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
Run Code Online (Sandbox Code Playgroud)

这不是一个理想的解决方案,因为我确信会有一些区域设置,在白天和月份之间格式化年份,这将创建一个时髦的字符串.但它适用于我所有测试过的案例.