首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从两个NSDates获取本地化日期范围字符串

从两个NSDates获取本地化日期范围字符串
EN

Stack Overflow用户
提问于 2014-07-08 02:51:04
回答 3查看 1.7K关注 0票数 8

当涉及到两个NSDate和显示范围的本地化字符串时,我遇到了一个问题。

例如,假设我的日期是7月7日和7月9日。我需要以下本地化字符串:

  • EN: 7月7日至9日
  • FR: 7-9朱丽叶
  • ES: 7-9 Julio
  • 德: 7.国际清算银行。9.朱利

显然,在这里使用NSString stringWithFormat:是行不通的。为了简单起见,我们甚至不要进入范围分别为两个月的情况。我知道如何为每个日期获得一个格式化的字符串,但它是在一个范围内格式化它,这让我。

有办法使用NSDateFormatter来获得这个吗?我越环顾四周,我就越认为我需要为每个区域设置一个开关。

编辑:为了澄清,我只需要用户的区域设置的日期范围。我不需要它们同时出现。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-07-08 18:47:34

经过进一步的研究,在iOS 8.0+中,您可以使用NSDateIntervalFormatter来完成这个任务。这对我现在没什么帮助,但知道它就在路上,我感到很欣慰。

票数 10
EN

Stack Overflow用户

发布于 2015-06-30 03:12:35

要详细说明Adam的答案,请使用一些示例代码:

代码语言:javascript
运行
复制
let formatter = NSDateIntervalFormatter()
formatter.dateStyle = NSDateIntervalFormatterStyle.ShortStyle
formatter.timeStyle = NSDateIntervalFormatterStyle.NoStyle
let dateRangeStr = formatter.stringFromDate(startDate, toDate: endDate)
票数 10
EN

Stack Overflow用户

发布于 2018-07-26 10:13:54

如果要删除年份信息,则需要显式地在dateTemplate中设置NSDateIntervalFormatter参数。

因此,只有这个解决方案,你将得到7月7日-9日的结果,没有日期。

目标-C

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
let df = DateIntervalFormatter()
df.dateTemplate = "MMMd"
let stringDate = df.string(from: Date(), to: Date().addingTimeInterval(10000))

文件是简单明了的:

代码语言:javascript
运行
复制
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"
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24622945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档