我在处理两个NSDate
并显示该范围的本地化字符串时遇到了问题。
例如,假设我的日期是7月7日和7月9日。我需要以下本地化字符串:
显然使用NSString stringWithFormat:
并不会在这里工作。为简单起见,我们甚至不会考虑您的范围是两个月的情况。我知道如何为每个日期获取格式化的字符串,但它会在一个范围内格式化它。
是否可以使用NSDateFormatter
来获取此信息?我越是环顾四周,我就越需要为每个区域设置切换。
编辑:为了澄清,我只需要用户所在区域的日期范围。我不同时需要所有这些。
答案 0 :(得分:9)
经过进一步研究后,在iOS 8.0+中,您可以使用NSDateIntervalFormatter
来执行此操作。这对我现在没有帮助,但是在途中了解它是令人欣慰的。
答案 1 :(得分:7)
用一些示例代码详细阐述Adam的答案:
let formatter = NSDateIntervalFormatter()
formatter.dateStyle = NSDateIntervalFormatterStyle.ShortStyle
formatter.timeStyle = NSDateIntervalFormatterStyle.NoStyle
let dateRangeStr = formatter.stringFromDate(startDate, toDate: endDate)
答案 2 :(得分:-1)
If you want to drop the year information you need to explicitly set the dateTemplate argument in NSDateIntervalFormatter.
So only with this solution you will get the result July 7-9 without date.
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]];
Swift
let df = DateIntervalFormatter()
df.dateTemplate = "MMMd"
let stringDate = df.string(from: Date(), to: Date().addingTimeInterval(10000))
Documentation is straightforward:
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"