SwiftyChrono
Swift 语言的自然语言日期解析器,用于从任何给定的文本中提取日期信息。
在将 Siri 集成到我们的 iOS 应用 时,我们发现 JavascriptCore 运行在资源受限的扩展上,并且会因为内存限制而崩溃。因此我们创建了一个 Swift 版本。感谢 Wanasit Tanakitrungruang 的 chrono.js。
SwiftyChrono 支持大多数日期和时间格式,例如:
- 今天、明天、昨天、上周五等
- 2013年8月17日 - 2013年8月19日
- 本周五从 13:00 - 16.00
- 5天前
- 2013年8月17日 Sat 18:40:39 GMT+0900 (JST)
- 2014-11-30T08:15:30-05:30
还有更多可用模式。您可以简单下载尝试。
状态
此项目目前正在 Quire iOS 应用中使用。
要求
Swift 4.2
- Xcode 10
- Swift 4.2
Swift 3
- iOS 9.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+
- Xcode 8
- Swift 3.0
- 64位设备(尚未在32位设备上测试)
安装
CocoaPods
use_frameworks!
target 'MyApp' do
pod 'SwiftyChrono'
end
使用
初始化
import SwiftyChrono
let chrono = Chrono()
解析
chrono.parse(text: "Bring a book tomorrow")
// [
// SwiftyChrono.ParsedResult(ref: 2017-02-22 08:33:33 +0000,
// index: 13,
// text: "tomorrow",
// tags: [
// SwiftyChrono.TagUnit.enCasualDateParser: true
// ],
// start: SwiftyChrono.ParsedComponents(
// knownValues: [
// SwiftyChrono.ComponentUnit.day: 23,
// SwiftyChrono.ComponentUnit.year: 2017,
// SwiftyChrono.ComponentUnit.month: 2],
// impliedValues: [
// SwiftyChrono.ComponentUnit.minute: 0,
// SwiftyChrono.ComponentUnit.second: 0,
// SwiftyChrono.ComponentUnit.millisecond: 0,
// SwiftyChrono.ComponentUnit.hour: 12
// ]),
// end: nil,
// isMoveIndexMode: false)
// ]
// refDate (1485921600000) is 2017/2/1 12:00:00.0000
let refDate = Date(timeIntervalSince1970: 1485921600)
// you can add a reference date
chrono.parse(text: "Bring a book tomorrow", refDate: refDate)
快速日期解析
chrono.parseDate(text: "Bring a book tomorrow", refDate: refDate)
// "Feb 2, 2017, 12:00 PM"
其他选项
// options: .forwardDate - the match date is always later than refDate
chrono.parseDate(text: "Bring a book on December 1", refDate: refDate)
// "Dec 1, 2016, 12:00 PM"
chrono.parseDate(text: "Bring a book on December 1", refDate: refDate, opt: [.forwardDate: 1])
// "Dec 1, 2017, 12:00 PM"
// you can assignee which hour in
// morning, afternoon, evening, noon
chrono.parseDate(text: "Bring a book tomorrow morning", refDate: refDate, opt: [.morning: 10])
// "Feb 2, 2017, 10:00 AM"
/// specify the preferred language will let the answer more acurate
chrono.parse(text: "you can do it tomorrow", refDate: refDate).map{ $0.text }
// ["do", "tomorrow"]
Chrono.preferredLanguage = .english
chrono.parse(text: "you can do it tomorrow", refDate: refDate).map{ $0.text }
// ["tomorrow"]
/// specify sixMinutesFixBefore1900 to true, if the date before 1900 is in your use case
Chrono.sixMinutesFixBefore1900 = true
chrono.parseDate(text: "you can do it 1970/1/1")
/// override defaut hour, minute, second, millisecond
// the default implied hour is 12 pm if the given text doesn't specify
Chrono.defaultImpliedHour = 1
Chrono.defaultImpliedMinute = 1
Chrono.defaultImpliedSecond = 1
Chrono.defaultImpliedMillisecond = 1
chrono.parseDate(text: "you can do it tomorrow", refDate: refDate)?.timeIntervalSince1970
// 1485968461.001, 2017/2/1 01:01:01.001