DateTools 实战指南:iOS 日期时间处理与时间段建模
DateTools 实战指南:iOS 日期时间处理与时间段建模
导读
DateTools 是一个专为 iOS(以及 macOS)设计的日期与时间处理库,同时提供 Objective-C 与 Swift 两个实现分支,目标是把 Date/NSDate 在使用上补齐到与其他语言(尤其是 .NET 的 DateTime 与 Time Period Library)同样顺手的水准。本文将以仓库根目录的 README.md 为主线,完整讲解它的安装方式、Time Ago 相对时间文案、日期组件读取、日期编辑与比较、日期格式化,以及最具特色的 Time Period(时间段)与其 Collection / Chain 两种分组模型,并结合仓库源码说明每个能力背后的实现机制。读完本文,你将能够直接用 DateTools 替代大量手写 NSCalendar/DateComponents 的样板代码,并为日程、排期类应用建立时间段运算的基础设施。
DateTools 概览:为什么需要它
原生的 Date/NSDate 只适合通过 timeIntervalSince... 这类 Unix 时间偏移来构建日期,并且保持"日历无关"(calendar agnostic)——它可以安全地表示时间点,却无法直接回答"现在是哪一年、哪一个月"这类基于日历组件的抽象问题。DateTools 的使命就是让日期类变得更完整:
- 免除读取日期组件时的样板代码;
- 提供更细腻、更布尔化的日期比较能力;
- 引入全新的"时间段(Time Period)"概念及其分组模型。
在仓库结构上,项目分为两个实现分支:
- Objective-C(Legacy):位于 DateTools/DateTools,核心为
NSDate+DateTools分类与DTTimePeriod*系列类; - Swift:位于 DateToolsSwift/DateTools,通过扩展
Date并引入TimeChunk、TimePeriod协议等实现。
两个分支都附带独立的示例工程(DateTools/Examples/DateToolsExample、DateToolsSwift/Examples/DateToolsExample)与独立的测试工程(DateTools/Tests、DateToolsSwift/Tests)。
安装方式
CocoaPods
在 Podfile 中按语言分支选择:
- Swift 版本:
pod 'DateToolsSwift' - Objective-C 版本(Legacy):
pod 'DateTools'
以仓库内的 DateTools.podspec 为准,Objective-C 版本号为 2.0.0,支持 iOS 7.0+ 与 OS X 10.7+,开启 requires_arc,source_files 指向 DateTools/DateTools,并把 DateTools.bundle 作为资源打进包内。
手动安装
所有类文件都位于仓库根目录的 DateTools 文件夹下。Swift 分支(位于 DateToolsSwift/DateTools)需要以下文件:
Constants.swiftDate+Bundle.swiftDate+Comparators.swiftDate+Components.swiftDate+Format.swiftDate+Inits.swiftDate+Manipulations.swiftDate+TimeAgo.swiftDateTools.bundleEnums.swiftInteger+DateTools.swiftTimeChunk.swiftTimePeriod.swiftTimePeriodChain.swiftTimePeriodCollection.swiftTimePeriodGroup.swift
Objective-C 分支(位于 DateTools/DateTools)需要:
DateTools.hNSDate+DateTools.{h,m}DTConstants.hDTError.{h,m}DTTimePeriod.{h,m}DTTimePeriodGroup.{h,m}DTTimePeriodCollection.{h,m}DTTimePeriodChain.{h,m}
其中 DateTools.h 汇总了所有头文件,若想一次性链接整个框架只需导入它。
DateTools.bundle 是国际化与 "Time Ago" 功能所必需的资源包,可在 Xcode 的 Project 菜单 → Info 下的 Localizations 子项中添加本地化。仓库内的 bundle 已内置 40 多种语言的 .strings 文件(见 DateTools/DateTools/DateTools.bundle 与 DateToolsSwift/DateTools/DateTools.bundle)。
Swift Package Manager
Swift 分支还提供了 Package.swift,声明了名为 DateToolsSwift 的 target,同样可以通过 SPM 集成(仓库根目录同时保留了 DateTools、Examples、Tests 等目录并已在包中排除)。
Time Ago:人性化的相对时间文案
任何日期库都少不了"把过去某个时刻转换成自然语言"的能力。DateTools 同时提供长格式与短格式(后者接近 Twitter 风格),调用方式如下(Swift):
let timeAgoDate = 2.days.earlier
print("Time Ago: ", timeAgoDate.timeAgoSinceNow)
print("Time Ago: ", timeAgoDate.shortTimeAgoSinceNow)
//Output:
//Time Ago: 2 days ago
//Time Ago: 2d
其中 2.days 这种"整数 + 单位"的链式语法由 Integer+DateTools.swift 提供:Int 扩展出 seconds、minutes、hours、days、weeks、months、years 七个计算属性,每个都返回一个只设置对应分量、其余为零的 TimeChunk。TimeChunk 是 TimeChunk.swift 中定义的结构体,本质是 Calendar 组件集合的轻量封装——它与按秒硬算的 TimeInterval 不同,会考虑夏令时、闰年等日历因素。
在 Objective-C 分支,对应 API 声明于 NSDate+DateTools.h:timeAgoSinceNow、shortTimeAgoSinceNow、weekTimeAgoSinceNow,以及可指定基准日期与 numericDates/numericTimes 参数的 timeAgoSinceDate:... 系列。
底层文案分级逻辑
从 Date+TimeAgo.swift 的 timeAgo(since:numericDates:numericTimes:) 实现可以看到完整的文案分级:先通过 NSCalendar.current 计算两个时刻之间的 [.second, .minute, .hour, .day, .weekOfYear, .month, .year] 分量,再按"年 ≥ 2 → 年 = 1 → 月 ≥ 2 → 月 = 1 → 周 ≥ 2 → 周 = 1 → 天 ≥ 2 → 昨天 → 小时 ≥ 2 → 小时 = 1 → 分钟 ≥ 2 → 分钟 = 1 → 秒 ≥ 3 → 刚刚"的顺序逐级回落;单数年/月/周/天/小时/分钟在默认情况下会输出 "Last year"、"Yesterday"、"An hour ago" 这类口语化文案,只有开启 numericDates/numericTimes 才转为 "1 year ago"、"1 hour ago" 的数字形式。短格式则一律输出 2y、3M、1w、2d、5h、10m、30s 这类缩写。
此外,实现中还包含针对俄语(ru)、乌克兰语(uk)的复数规则处理(getLocaleFormatUnderscoresWithValue),会根据数值的十位/个位选择 ""、"_"、"__" 三种词形后缀,这也是该库本地化深度的体现。所有文案通过 DateToolsLocalizedStrings 从 DateTools.bundle 的 DateTools 字符串表中读取。
支持的语言
在把对应本地化文件加入工程后,DateTools 目前支持以下语言:
ar(阿拉伯语)、bg(保加利亚语)、ca(加泰罗尼亚语)、zh_Hans(简体中文)、zh_Hant(繁体中文)、cs(捷克语)、da(丹麦语)、nl(荷兰语)、en(英语)、fi(芬兰语)、fr(法语)、de(德语)、gre(希腊语)、gu(古吉拉特语)、he(希伯来语)、hi(印地语)、hu(匈牙利语)、is(冰岛语)、id(印尼语)、it(意大利语)、ja(日语)、ko(韩语)、lv(拉脱维亚语)、ms(马来语)、nb(挪威语)、pl(波兰语)、pt(葡萄牙语)、ro(罗马尼亚语)、ru(俄语)、sl(斯洛文尼亚语)、es(西班牙语)、sv(瑞典语)、th(泰语)、tr(土耳其语)、uk(乌克兰语)、vi(越南语)、cy(威尔士语)、hr(克罗地亚语)。
该库的 Time Ago 能力继承自 Kevin Lawler 的 NSDate+TimeAgo 项目,后者已被正式合并进本库。
Date Components:免样板地读取日期组件
从日期中提取组件本来要做很多铺垫:创建日历、声明组件标志、再从日历中提取。用 DateTools,这段代码:
//Create calendar
let calendar = Calendar(identifier: .gregorian)
let dateComponents = calendar.dateComponents(Set<Calendar.Component>([.month,.year]), from: Date())
//Get components
let year = dateComponents.year!
let month = dateComponents.month!
变成了:
let year = Date().year
let month = Date().month
Objective-C 分支在 NSDate+DateTools.h 中定义了完整的组件读取集合,无需显式指定日历即可使用:era、year、month、day、hour、minute、second、weekday、weekdayOrdinal、quarter、weekOfMonth、weekOfYear、yearForWeekOfYear、daysInMonth、dayOfYear、daysInYear,以及 isInLeapYear、isToday、isTomorrow、isYesterday、isWeekend、isSameDay: 等便捷判断。若需要指定日历,同一头文件还提供了对应的 xxxWithCalendar: 变体(NSDate+DateTools.h),并可通过 NSDate+DateTools.h 的 defaultCalendarIdentifier / setDefaultCalendarIdentifier: 统一管理默认日历标识。
Swift 分支对应能力分散在 Date+Components.swift(组件读取)与 Date+Inits.swift(Date(year:month:day:hour:minute:second:) 等便捷构造器)中。
Date Editing:加减组件移动日期
日期编辑方法让"把日期向前或向后移动若干组件"变成一行调用。例如要得到一个比给定日期晚 1 年的日期,传统写法是:
//Create calendar
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:[NSDate defaultCalendar]];
NSDateComponents *components = [[NSDateComponents alloc] init];
//Make changes
[components setYear:1];
//Get new date with updated year
NSDate *newDate = [calendar dateByAddingComponents:components toDate:date options:0];
用 DateTools 只需:
NSDate *newDate = [date dateByAddingYears:1];
减法同样完整支持,通过 dateBySubtractingYears 等方法实现。完整的编辑方法集定义于 NSDate+DateTools.h:dateByAddingYears/Months/Weeks/Days/Hours/Minutes/Seconds 与对应的 dateBySubtracting* 共 14 个方法,覆盖从秒到年的七个时间单位。值得注意的是这些运算走的是日历组件运算而非固定秒数,因此能正确处理月末、闰年等边界(例如 1 月 31 日加 1 个月)。
Swift 分支除了 Date + TimeChunk 的加减运算外,Date+Manipulations.swift 还提供了 start(of:) 与 end(of:):前者把指定组件及更小组件归零(如 .day 会把时分秒清零、.year 会回到 1 月 1 日零点),后者把更小组件置为最大值(如 .month 会回到当月最后一天的 23:59:59.999)。
Date Comparison:更灵活、更布尔化的日期比较
原生 NSDate 只提供四个基础比较方法:isEqualToDate:、earlierDate:、laterDate:、compare:。earlierDate:/laterDate: 适合取极值,但写业务逻辑时我们更常需要"这个日期是否早于那个日期"这样的布尔答案。DateTools 补充了:
isEarlierThan:isEarlierThanOrEqualTo:isLaterThan:isLaterThanOrEqualTo:
同时,当需要"两个日期相差多少年/多少天"这类带单位的结果时,原生方法只能给出以秒计的 timeIntervalSinceDate:,而 DateTools 把 NSCalendar 的复杂运算全部抽象掉了。传统写法:
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:[NSDate defaultCalendar]];
NSDate *earliest = [firstDate earlierDate:secondDate];
NSDate *latest = (secondDate == firstDate) ? secondDate : firstDate;
NSInteger multiplier = (secondDate == firstDate) ? -1 : 1;
NSDateComponents *components = [calendar components:allCalendarUnitFlags fromDate:earliest toDate:latest options:0];
NSInteger yearsApart = multiplier*(components.month + 12*components.year);
变成:
NSInteger yearsApart = [firstDate yearsFrom:secondDate];
该分类下的比较方法集(见 NSDate+DateTools.h)以年/月/周/天/小时/分钟/秒七个单位为轴,每组四到七种形态:
- 差值形态:
yearsFrom:、monthsFrom:、weeksFrom:、daysFrom:(小时及以下返回 double),并可传入calendar:参数; - 相对"现在"形态:
yearsUntil/yearsAgo等; - 相对指定日期形态:
yearsEarlierThan:/yearsLaterThan:等。
Swift 端对应实现于 Date+Comparators.swift,并提供 chunkBetween(date:) 方法:返回一个以"年/月/日/时/分/秒"自然形态表达的 TimeChunk(例如两个生日之间会得到 TimeChunk(seconds: 0, minutes: 37, hours: 0, days: 13, weeks: 0, months: 10, years: 0)),非常适合计算年龄、工龄等场景;传入未来日期时各分量为正,传入过去日期时各分量为负。
Formatted Date Strings:一行生成格式化字符串
DateTools 顺手提供了两个快速格式化方法(README 原话:"Just for kicks"):
formattedDateWithStyle::按NSDateFormatterStyle风格输出,如.short、.medium、.long、.full;formattedDateWithFormat::按自定义格式串输出。
两者都提供带 timeZone: 与 locale: 参数的变体,未指定时默认使用当前时区与当前 locale(Swift 端在 Date+Format.swift 中默认取 TimeZone.autoupdatingCurrent 与 Locale.autoupdatingCurrent)。注意这是刻意保持"轻量"的便捷方法,复杂格式化需求仍建议直接使用 DateFormatter。
Time Periods:时间段建模
日期是离散的点,但现实世界由一段段时间构成——一个下午的约会、一周的假期。DateTools 用 TimePeriod(Swift 端为 TimePeriodProtocol)表示时间段,并配套了初始化、信息查询、操作与关系判断等一整套方法。Objective-C 实现位于 DTTimePeriod.h / DTTimePeriod.m,Swift 实现位于 TimePeriod.swift。
初始化
时间段由开始日期与结束日期构成,最基本的初始化方式是:
DTTimePeriod *timePeriod = [[DTTimePeriod alloc] initWithStartDate:startDate endDate:endDate];
除了 initWithStartDate:endDate: 外,工厂方法还支持"已知长度 + 锚定一端"的创建模式(完整清单见 DTTimePeriod.h):
timePeriodWithSize:startingAt:/timePeriodWithSize:amount:startingAt::以某时刻为起点,向前延伸指定大小(amount为倍数);timePeriodWithSize:endingAt:/timePeriodWithSize:amount:endingAt::以某时刻为终点,向后延伸指定大小;timePeriodWithAllTime:覆盖distantPast到distantFuture的最大区间。
例如创建一个"从当前时刻开始、恰好 5 小时"的时间段:
DTTimePeriod *timePeriod = [DTTimePeriod timePeriodWithSize:DTTimePeriodSizeHour amount:5 startingAt:[NSDate date]];
DTTimePeriodSize 枚举定义了七个单位:DTTimePeriodSizeSecond、Minute、Hour、Day、Week、Month、Year(DTTimePeriod.h)。从实现看,timePeriodWithSize:amount:startingAt: 内部调用 dateWithAddedTime:amount:baseDate:(DTTimePeriod.m),后者按单位分发到 dateByAddingSeconds: 等编辑方法,从而保证月份、年份等非定长单位的正确性;endingAt: 系列则对称地走 dateWithSubtractedTime:amount:baseDate:。
时间段信息
DTTimePeriod 提供以下查询方法(DTTimePeriod.h):
hasStartDate:是否有开始日期(StartDate 非 nil);hasEndDate:是否有结束日期(EndDate 非 nil);isMoment:开始与结束日期相同,即"瞬间";durationInYears/durationInWeeks/durationInDays/durationInHours/durationInMinutes/durationInSeconds:以指定单位返回区间长度。
其中 isMoment 与各 durationIn... 的实现都要求起止日期同时存在,否则分别返回 NO 与 0(见 DTTimePeriod.m)。
操作:平移与伸缩
时间段可以整体平移(Shifting),也可以以某一点为锚进行伸缩(Lengthening / Shortening)。
平移(Shifting):平移会同时把开始与结束日期按请求的量向前或向后移动。向前调用 shiftEarlierWithSize:amount:,向后调用 shiftLaterWithSize:amount:,amount 作为倍数。实现即对 StartDate 与 EndDate 同步应用 dateWithSubtractedTime: / dateWithAddedTime:(DTTimePeriod.m)。
伸缩(Lengthening / Shortening):伸缩时锚定时间段的一端(DTTimePeriodAnchorStart / DTTimePeriodAnchorEnd),只改变另一端;也可锚定中心点(DTTimePeriodAnchorCenter),同时改变起止两端。锚定枚举定义于 DTTimePeriod.h。例如把一段 1 分钟的时间段加长到 2 分钟,锚定其结束时刻:
DTTimePeriod *timePeriod = [DTTimePeriod timePeriodWithSize:DTTimePeriodSizeMinute endingAt:[NSDate date]];
[timePeriod lengthenWithAnchorDate:DTTimePeriodAnchorEnd size:DTTimePeriodSizeMinute amount:1];
这样"现在"这个结束时刻被保留,只有开始时刻被提前 1 分钟。锚定中心的实现会把 amount 平分到两端(amount/2 做加减,见 DTTimePeriod.m),因此奇数倍数在中心锚定下会出现舍入,使用时值得留意。
关系:两个时间段如何互相定位
在排期类应用里,经常需要回答"两个时间段是否相同?一个是否在另一个内部?"。DTTimePeriod 提供如下基本关系方法(DTTimePeriod.h):
isEqualToPeriod::起止日期完全一致;isInside::接收方被给定时间段完整包含;contains::接收方完整包含给定时间段;overlapsWith::存在共享区间(不含"一端恰好等于另一端"这种瞬时接触);intersects::存在共享区间(含瞬时接触);gapBetween::两段不相交时的间隔秒数,相交则返回 0。
更精确地,可以通过 relationToPeriod: 获取官方定义的 13 种关系枚举之一:
-(DTTimePeriodRelation)relationToPeriod:(DTTimePeriod *)period;
所有可能关系在 DTTimePeriodRelation 枚举中列出(DTTimePeriod.h):
After、StartTouching、StartInside、InsideStartTouching、EnclosingStartTouching、Enclosing、EnclosingEndTouching、ExactMatch、Inside、InsideEndTouching、EndInside、EndTouching、Before,外加起止日期不完整时的 None。判断逻辑在 DTTimePeriod.m 中按"另一端结束是否早于本端开始""两端是否相切""一端是否内含"等条件逐级分支。Swift 端对应枚举 Relation 定义于 Enums.swift,语义与上述 13 种一一对应。
此外,containsDate:interval: 可判断某日期是否落在时间段内,DTTimePeriodInterval 的 Open(不包含边界)与 Closed(包含边界)两种语义分别对应严格不等式与含等号比较(DTTimePeriod.m)。示例应用的 "Time Periods" 标签页支持拖动时间段实时观察关系变化,是理解这些关系最直观的途径(示例代码见 DateTools/Examples/DateToolsExample/DateToolsExample/TimePeriodsViewController.m 与 DateToolsSwift/Examples/DateToolsExample/DateToolsExample/TimePeriodsViewController.swift)。
Time Period Groups:时间段的分组抽象
时间段分组的基类为 DTTimePeriodGroup(DTTimePeriodGroup.h),它同时提供数组式下标访问(objectAtIndexedSubscript: / setObject:atIndexedSubscript:)、分组级 StartDate / EndDate 属性、各单位的 durationIn... 汇总方法与整体平移操作。分组派生出两种语义截然不同的类型:
DTTimePeriodCollection:松散集合,允许重叠;DTTimePeriodChain:紧密链条,不允许重叠。
两者操作方式都类似 NSArray,可以 add / insert / remove 时间段,区别在于内部对这些时间段的组织逻辑。
Time Period Collections:允许重叠的松散集合
集合是时间段的松散集合:除非你主动排序,否则它们保持无序;集合自身拥有从内部时间段推导出的 StartDate / EndDate;允许集合内时间段互相重叠。创建与使用:
//Create collection
DTTimePeriodCollection *collection = [DTTimePeriodCollection collection];
//Create a few time periods
DTTimePeriod *firstPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2014 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"]];
DTTimePeriod *secondPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2016 11 05 18:15:12.000"]];
//Add time periods to the collection
[collection addTimePeriod:firstPeriod];
[collection addTimePeriod:secondPeriod];
//Retrieve collection items
DTTimePeriod *firstPeriod = collection[0];
排序:集合提供三种排序维度、六个方法(DTTimePeriodCollection.h):
- 按开始日期:
sortByStartAscending/sortByStartDescending - 按结束日期:
sortByEndAscending/sortByEndDescending - 按时间段时长:
sortByDurationAscending/sortByDurationDescending
关系运算:集合支持查询某日期或某时间段与集合的关系,例如找出所有与某日期相交的时间段:
DTTimePeriodCollection *result = [collection periodsIntersectedByDate:someDate];
完整的方法集(DTTimePeriodCollection.h)包括:
periodsInside::位于给定时间段内部的所有时间段;periodsIntersectedByDate::与给定日期相交的时间段(结果仍是新的DTTimePeriodCollection);periodsIntersectedByPeriod::与给定时间段相交的时间段;periodsOverlappedByPeriod::与给定时间段重叠的时间段;isEqualToCollection:considerOrder::两个集合的完整相等性检查,可指定是否考虑顺序。
Time Period Chains:不允许重叠的紧密链条
链条是紧密耦合的时间段集合:始终按起止日期组织,同样有自己的 StartDate / EndDate,但不允许内部时间段重叠,非常适合建模"连续会议""串行日程"这类场景。创建与使用:
//Create chain
DTTimePeriodChain *chain = [DTTimePeriodChain chain];
//Create a few time periods
DTTimePeriod *firstPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2014 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"]];
DTTimePeriod *secondPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2016 11 05 18:15:12.000"]];
//Add test periods
[chain addTimePeriod:firstPeriod];
[chain addTimePeriod:secondPeriod];
//Retrieve chain items
DTTimePeriod *firstPeriod = chain[0];
链条的底层规则值得注意:每当向链条添加一个时间段,它保留自己的时长,但其 StartDate 会被修正为链条中最新时间段的 EndDate,以此维持链条的紧密衔接结构。插入行为分两种:
- 插入在索引 0 之外的位置时,插入点之后的所有时间段会按新时间段的时长整体后移,插入点之前的时间段保持不变;
- 插入在索引 0 时,集合整体的 StartDate 会按新时间段的时长平移。
除基本操作外,链条还提供 removeLatestTimePeriod / removeEarliestTimePeriod、isEqualToChain: 相等性检查,以及继承自分组的整体前移/后移能力(见 DTTimePeriodChain.h)。更详细的插入位移算法可以继续阅读 DTTimePeriodChain.m 与对应测试 DateTools/Tests/DateToolsTests/DateToolsTestsTests/DTTimePeriodChainTests.m。
单元测试与质量保证
两个分支都针对所有主要类编写了单元测试,位于仓库顶层 Tests 目录下:
- Objective-C:
DateTools/Tests/DateToolsTests/DateToolsTestsTests/下的DTTimeAgoTests.m、DTTimePeriodTests.m、DTTimePeriodGroupTests.m、DTTimePeriodCollectionTests.m、DTTimePeriodChainTests.m与DateToolsTests.m,覆盖初始化、工厂方法、排序、插入/删除、平移与关系判断等行为; - Swift:
DateToolsSwift/Tests/DateToolsTests/DateToolsTestsTests/下的DateComparatorsExtensionTests.swift、DateComponentsExtensionTests.swift、DateFormatExtensionTests.swift、DateInitsExtensionTests.swift、DateManipulationsExtensionTests.swift、DateTimeAgoExtensionTests.swift、IntegerExtensionTests.swift、TimeAgoTests.swift、TimeChunkTests.swift、TimePeriodTests.swift、TimePeriodCollectionTests.swift、TimePeriodChainTests.swift、TimePeriodGroupTests.swift等。
README 中说明该库累计包含超过 300 个测试用例,并通过 Travis CI 进行持续集成测试;若发现测试用例不完整,可以提交 issue 协助修复。
常量与文档
为支持各单位的运算,DTConstants.h(Objective-C)与 Constants.swift(Swift)定义了一组时间常量,例如 SECONDS_IN_YEAR(31536000)、SECONDS_IN_WEEK(604800)、SECONDS_IN_DAY(86400)、SECONDS_IN_HOUR(3600)、SECONDS_IN_MINUTE(60)等;Swift 端还额外提供闰年(SecondsInLeapYear = 31622400)与各月天数对应的秒常量,以及 AllCalendarUnitFlags 全集标志,供需要手写日历运算的场合使用。
所有方法与变量均带注释文档,支持在 Xcode 中像 SDK 类一样 Option+Click 查看说明,包括方法作用与输入/输出参数含义。若发现文档存在歧义,可以在仓库提交 issue 反馈。
许可与致谢
DateTools 以 MIT 协议开源(见仓库 LICENSE),Copyright (c) 2014 Matthew York,允许自由使用、复制、修改与再分发。
致谢部分(详见 README.md 与 CREDITS.md):Grayson Webster 主导了 Swift 分支的重写;Kevin Lawler 的 NSDate+TimeAgo 工作奠定了 Time Ago 能力的基础并已合并入库;设计理念上深受 .NET DateTime 结构与 .NET 的 Time Period Library(Jani Giannoudis 的 ITimePeriod 工作)启发,时间段关系示意图亦源自该库。
结语
DateTools 的价值在于把三类高频需求压缩成一行 API:基于组件的日期读写与编辑、带单位的日期比较、以及时间段(含集合与链条)建模。从源码可以看到,它在底层仍然依赖 NSCalendar 与 NSDateComponents,但把所有样板逻辑封装进了分类方法与工厂方法中——这正是它"让日期和时间变得简单"的落点。对于需要在 iOS/macOS 上快速实现时间线、排期、连续日程等功能的开发者,建议先从 README.md 的示例入手,再结合 NSDate+DateTools.h、DTTimePeriod.h、DTTimePeriodCollection.h、DTTimePeriodChain.h 等头文件逐项确认 API 行为,并参考两个分支的测试用例验证边界情况。