MGEDateFormatter 2.0.1

MGEDateFormatter 2.0.1

测试已测试
Lang语言 SwiftSwift
许可证 MIT
发布上次发布2016年10月
SPM支持 SPM

Manuel García-Estañ 维护。



MGEDateFormatter

MGEDateFormatter 已弃用。请使用 November 代替。

MGEDateFormatter 提供了对 Date 和 DateFormatter 的一系列扩展,以构建一个美观的 API,简化了从 Date 到 NSString 以及反方向的转换。

创建 DateFormatter 是一项耗时的任务。因此,MGEDateFormatter 守护着创建的 DateFormatter 的缓存,以在应用程序的生命周期内重复使用它们。

此项目的目的是提供一个优雅的 API 来从 Date 实例获取字符串表示。

let stringWithStyles = date.string(dateStyle: .medium, timeStyle: .none)
let stringWithTemplate = date.string(withTemplate: "MMMMyyyy")
let stringWithFormat = date.string(withFormat: "MM/yy")
let monthAndYearString = date.string(with: .monthAndYear)

继续阅读,了解如何实现这个过程!

这是库的 Swift 3 版本。Swift 2 版本 在这里可查

安装

将以下内容添加到您的 Podfile

pod 'MGEDateFormatter'

然后运行 pod install

最后,在需要 MGEDateFormatter 的类中

import MGEDateFormatter

如果您未安装或集成 CocoaPods,您可以在这里学习如何做到这一点:

这里

用法

将 Date 转换为 String 有三种主要方式。

使用 DateFormatter.Style
let date = Date()
let string = date.string(dateStyle: .shortStyle, timeStyle: .shortStyle)

如有需要,您可以为转换提供自定义区域

let spanishLocale = Locale(localeIdentifier: "es")
let date = Date()
let string = date.string(dateStyle: .mediumStyle, timeStyle: .noStyle, locale: spanishLocale)
使用模板中的格式
let date = Date()
let string = date.string(withTemplate: "MMMyyyy")

如有需要,您可以为转换提供自定义区域

let spanishLocale = Locale(localeIdentifier: "es")
let date = Date()
let string = date.string(withTemplate: "MMMyyyy", locale: spanishLocale)
使用日期格式
let date = Date()
let string = date.string(withFormat: "MM/dd/yyyy HH:mm:ss")

如有需要,您可以为转换提供自定义区域

let spanishLocale = Locale(localeIdentifier: "es")
let date = Date()
let string = date.string(withFormat: "MM/dd/yyyy HH:mm:ss", locale: spanishLocale)

String 到 Date

同样的,也有三种方式从 String 创建 Date。它们都作为 Date 初始化器提供

使用 DateFormatter.Style
let string = "11/18/83, 11:30 AM"
let convertedDate = Date(string: string, dateStyle: .shortStyle, timeStyle: .shortStyle)

注意:转换后的 convertedDate 是 Optional,如果字符串无法解析,则将为 nil

如有需要,您可以为转换提供自定义区域

let spanishLocale = Locale(localeIdentifier: "es")
let string = "18/11/83 11:30"
let convertedDate = Date(string: string, dateStyle: .shortStyle, timeStyle: .shortStyle, locale: spanishLocale)
使用模板格式
let string = "November 18, 1983, 11:30"
let convertedDate = Date(string: string, template: "ddMMMMyyyyHHmm")

注意:转换后的 convertedDate 是 Optional,如果字符串无法解析,则将为 nil

如有需要,您可以为转换提供自定义区域

let spanishLocale = Locale(localeIdentifier: "es")
let string = "noviembre 18, 1983, 11:30"
let convertedDate = Date(string: string, template: "ddMMMMyyyyHHmm", locale: spanishLocale)
使用日期格式
let string = "18/November/1983 11:30"
let convertedDate = Date(string: string, format: "dd/MMMM/yyyy HH:mm")

注意:转换后的 convertedDate 是 Optional,如果字符串无法解析,则将为 nil

如有需要,您可以为转换提供自定义区域

let spanishLocale = Locale(localeIdentifier: "es")
let string = "18/noviembre/1983 11:30"
let convertedDate = Date(string: string, format: "dd/MMMM/yyyy HH:mm", locale: spanishLocale)

最佳实践

在我的应用中,我喜欢这样使用MGEDateFormatter

1. 创建一个包含我的日期格式化模板和/或格式的枚举

通常我只有一组少量的模板和/或格式要使用。我将它们封装到几个枚举中。

enum DateTemplate: String {
    case monthAndYear = "MMMyyyy"
    case fullShortDate = "ddMMyy"
}

enum DateFormat: String {
    case fullDate = "dd/MM/yyyy"
    case fullDateAndTime = "dd/MM/yyyy HH:mm:ss"
}

2. 创建一个Date扩展

我创建了一个扩展,它封装了MGEDateFormatter的方法,以便接受定义的枚举的值。

extension Date {

    // MARK: Helpers Date -> String

    func string(with template: DateTemplate) -> String {
        return string(withTemplate: template.rawValue)
    }

    func string(with format: DateFormat) -> String {
        return string(withFormat: format.rawValue)
    }

    // MARK: Helpers String -> Date

    convenience init?(string: String, template: DateTemplate) {
        self.init(string: string, template: template.rawValue)
    }

    convenience init?(string: String, format: DateFormat) {
        self.init(string: string, format: format.rawValue)
    }
}

3. 从扩展中调用方法

现在,我们有一个非常简单、快速、易用的API,可以将日期转换为字符串,再转回日期。

let date = Date()

// Templates
let monthAndYearString = date.string(with: .monthAndYear)
let fullShortDateString = date.string(with: .fullShortDate)

let dateFromMonthAndYear = Date(string: "11/1983", template: .monthAndYear)

// Formats
let fullDateString = date.string(with: .fullDate)
let fullDateAndTimeString = date.string(with: .fullDateAndTime)

let dateFromfullDateString = Date(string: "11/18/1983", format: .fullDate)

自定义格式化器

提供的三个格式化字符串的方法还不够吗?不用担心,你仍然可以利用MGEDateFormatter

如果你想对你的格式化器进行进一步的定制,你可以使用DateFormatterProvider协议。

要遵守此协议,你需要重写一个属性(cacheKey)和一个函数(configure(_: DateFormatter))。这里有一个例子

class MyDateFormatterProvider: DateFormatterProvider {
    let cacheKey: String
    let format: String

    init(format: String) {
        self.format = format
        self.cacheKey = "MyConfigurator(\(format))"
    }

    func configure(formatter: DateFormatter) {
        formatter.dateFormat = format
        formatter.monthSymbols = ["JN", "FB", "MR", "AP", "MY", "JN", "JL", "AG", "SP", "OT", "NV", "DC"]
        // whatever configuration you need
    }
}

然后,以后

let myProvider = MyDateFormatterProvider(format: "dd MMMM yyyy")

// from date to string
let date = Date()
let myCustomFormatString = date.string(with: myProvider)

// from string to date
let string = "18 NV 1983"
let convertedDate = Date(string: string, provider: myProvider)

用于序列化DateStringDateFormatter将被缓存在定义的cacheKey下,并在需要再次使用时很好地重用。换句话说,如果在应用的任何其他点我们创建了一个与这个相同的格式的新提供商

let otherProvider = MyDateFormatterProvider(format: "dd MMMM yyyy")

// from date to string
let otherDate = Date()
let otherCustomFormatString = date.string(with: otherProvider)

DateFormatter将被重用。

不缓存格式化器

如果你不介意缓存格式化器,你可以简单地使用Date扩展将DateString转换回来,或反之,使用一个DateFormatter

let formatter = DateFormatter()
formatter.dateFormat = "MM/yyyy"

let string = Date().string(with: formatter)
let date = Date(string: "06/2016, formatter: formatter")


联系信息

Manuel García-Estañ Martínez
@manueGE

许可证

MGEDateFormatter可在MIT许可证下使用。