Ada*_*o13 7 localization objective-c nsdate nsdateformatter ios
当涉及到两个NSDates并显示范围的本地化字符串时,我遇到了一个问题.
例如,假设我的日期是7月7日和7月9日.我需要以下本地化字符串:
显然使用NSString stringWithFormat:不会在这里工作.为简单起见,我们甚至不介绍你的范围是两个月的情况.我知道如何为每个日期获取格式化的字符串,但它在一个范围内将其格式化.
有没有办法使用一个NSDateFormatter来获得这个?我越是环顾四周,我就越需要为每个语言环境设置一个开关.
编辑:为了澄清,我只需要用户的语言环境的日期范围.我不需要同时使用所有这些.
用一些示例代码详细说明Adam的答案:
let formatter = NSDateIntervalFormatter()
formatter.dateStyle = NSDateIntervalFormatterStyle.ShortStyle
formatter.timeStyle = NSDateIntervalFormatterStyle.NoStyle
let dateRangeStr = formatter.stringFromDate(startDate, toDate: endDate)
Run Code Online (Sandbox Code Playgroud)
如果你想删除年份信息,你需要在 NSDateIntervalFormatter 中显式设置 dateTemplate 参数。
因此,只有使用此解决方案,您才能获得 7 月 7 日至 9 日的结果(没有日期)。
Objective-C
NSDate *startDate = [NSDate new];
NSDate *endDate = [[NSDate new] dateByAddingTimeInterval:10000];
NSDateIntervalFormatter *df = [[NSDateIntervalFormatter alloc] init];
df.dateTemplate = @"MMMd";
NSString *detailedString = [df stringFromDate:startDate toDate:
[trip.startDate dateByAddingNumberOfDays:endDate]];
Run Code Online (Sandbox Code Playgroud)
迅速
let df = DateIntervalFormatter()
df.dateTemplate = "MMMd"
let stringDate = df.string(from: Date(), to: Date().addingTimeInterval(10000))
Run Code Online (Sandbox Code Playgroud)
文档很简单:
If the range smaller than the resolution specified by the dateTemplate, a single date format will be produced. If the range is larger than the format specified by the dateTemplate, a locale-specific fallback will be used to format the items missing from the pattern.
For example, if the range is 2010-03-04 07:56 - 2010-03-04 19:56 (12 hours)
- The pattern jm will produce
for en_US, "7:56 AM - 7:56 PM"
for en_GB, "7:56 - 19:56"
- The pattern MMMd will produce
for en_US, "Mar 4"
for en_GB, "4 Mar"
If the range is 2010-03-04 07:56 - 2010-03-08 16:11 (4 days, 8 hours, 15 minutes)
- The pattern jm will produce
for en_US, "3/4/2010 7:56 AM - 3/8/2010 4:11 PM"
for en_GB, "4/3/2010 7:56 - 8/3/2010 16:11"
- The pattern MMMd will produce
for en_US, "Mar 4-8"
for en_GB, "4-8 Mar"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1148 次 |
| 最近记录: |