swift 日期转换工具类

使用 enum 转换时间

也可以使用 class struct, 我这里使用 enum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 时间转换工具类
enum DateUtil{
// ...
}
extension DateUtil {
enum DateFormat: String {
case ymd = "yyyy-MM-dd"
case ymdhms = "yyyy-MM-dd HH:mm:ss"
case ymdhmsS = "yyyy-MM-dd HH:mm:ss.SSS"

var formatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = self.rawValue
return dateFormatter
}

func dateFrom(string: String) -> Date? {
return formatter.date(from: string)
}

func stringFrom(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = self.rawValue
return dateFormatter.string(from: date)
}

}
}

使用 extension 转换时间

1
2
3
4
5
6
7
8
9
10
11
// 扩展
extension Date {
static let timeFormatter: DateFormatter = {
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss "
return timeFormatter
}()
var toString: String {
return Date.timeFormatter.string(from: self)
}
}

使用

1
2
3
4
5
let date = Date()

let dateStrByEnum = DateUtil.DateFormat.ymdhmsS.stringFrom(date: date)

let dateStrByExtension = date.toString

本文标题:swift 日期转换工具类

文章作者:史彦超

发布时间:2018年10月24日 - 11:10

最后更新:2021年07月20日 - 16:07

原始链接:https://doingself.github.io/2018/10/24/swift-%E6%97%A5%E6%9C%9F%E8%BD%AC%E6%8D%A2%E5%B7%A5%E5%85%B7%E7%B1%BB/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Donate comment here