我有数据类型为日期的变量,我以这种格式存储日期
2018-12-24 18:00:00 UTC
我怎样才能从这一天或这个月得到?
最佳答案
细节
链接
How to convert string to Date
解决方案
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))")
关于swift - 如何从日期类型中获取日期和月份 - swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53356392/