当涉及到两个NSDate和显示范围的本地化字符串时,我遇到了一个问题。
例如,假设我的日期是7月7日和7月9日。我需要以下本地化字符串:
显然,在这里使用NSString stringWithFormat:是行不通的。为了简单起见,我们甚至不要进入范围分别为两个月的情况。我知道如何为每个日期获得一个格式化的字符串,但它是在一个范围内格式化它,这让我。
有办法使用NSDateFormatter来获得这个吗?我越环顾四周,我就越认为我需要为每个区域设置一个开关。
编辑:为了澄清,我只需要用户的区域设置的日期范围。我不需要它们同时出现。
发布于 2014-07-08 18:47:34
经过进一步的研究,在iOS 8.0+中,您可以使用NSDateIntervalFormatter来完成这个任务。这对我现在没什么帮助,但知道它就在路上,我感到很欣慰。
发布于 2015-06-30 03:12:35
要详细说明Adam的答案,请使用一些示例代码:
let formatter = NSDateIntervalFormatter()
formatter.dateStyle = NSDateIntervalFormatterStyle.ShortStyle
formatter.timeStyle = NSDateIntervalFormatterStyle.NoStyle
let dateRangeStr = formatter.stringFromDate(startDate, toDate: endDate)发布于 2018-07-26 10:13:54
如果要删除年份信息,则需要显式地在dateTemplate中设置NSDateIntervalFormatter参数。
因此,只有这个解决方案,你将得到7月7日-9日的结果,没有日期。
目标-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))文件是简单明了的:
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"https://stackoverflow.com/questions/24622945
复制相似问题