我现在基本上有了这段代码,我正在尝试通过在中间换行来格式化,但它没有给我换行。我这样做正确吗?
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_DB"];
dateFormatter.locale = twoHourLocale;
formatString = [NSDateFormatter dateFormatFromTemplate:@"EEEE \n hh:mm" options:0 locale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:formatString];
最佳答案
I basically have this code right now and I am trying to format by having a new line in between but it doesn't give me a new line. Am I doing it correctly?
调用-dateFormatFromTemplate:locale:options:
的要点是返回针对指定区域设置正确格式化的格式字符串。也就是说,该方法会查看您指定的日期组件,并根据本地习惯进行排列,例如在美国为“2019 年 1 月 2 日”,在欧洲为“2 Jan 2019”。我认为它基本上忽略了模板中它无法识别为日期组件说明符的任何部分。如果它正在移动日期组件,它如何知道在哪里放置它不知道的非日期部分?
如果您不关心不同的区域设置并且只想要一个包含换行符的日期,那么您可以跳过该方法并自行创建模板字符串:
formatString = @"EEEE \n hh:mm";
[dateFormatter setDateFormat:formatString];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", dateString);
上面的代码将在工作日和时间之间使用换行符记录当前日期,因此 -stringFromDate:
将很乐意使用您的格式字符串并保留换行符。
如果您确实关心区域设置但仍然想要换行符,则您必须创建自己的特定于区域设置的日期格式字符串,或者调用 -dateFormatFromTemplate:locale:options:
然后在结果中的正确位置插入换行符。
关于ios - 如何在 Objective C 中格式化日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54991485/