首页 > 解决方案 > 如何从日期类型中获取日期和月份 - swift 4

问题描述

我有数据类型为 Date 的变量,我以这种格式存储了日期

2018-12-24 18:00:00 UTC

我怎样才能从这一天或这一月得到?

标签: swiftdate

解决方案


细节

  • Xcode 版本 11.0 (11A420a),Swift 5

链接

如何将字符串转换为日期

解决方案

extension Date {
    func get(_ components: Calendar.Component..., calendar: Calendar = Calendar.current) -> DateComponents {
        return calendar.dateComponents(Set(components), from: self)
    }

    func get(_ component: Calendar.Component, calendar: Calendar = Calendar.current) -> Int {
        return calendar.component(component, from: self)
    }
}

用法

let date = Date()

// MARK: Way 1

let components = date.get(.day, .month, .year)
if let day = components.day, let month = components.month, let year = components.year {
    print("day: \(day), month: \(month), year: \(year)")
}

// MARK: Way 2

print("day: \(date.get(.day)), month: \(date.get(.month)), year: \(date.get(.year))")

推荐阅读