swift - 如何从日期类型中获取日期和月份 - swift 4
问题描述
我有数据类型为 Date 的变量,我以这种格式存储了日期
2018-12-24 18:00:00 UTC
我怎样才能从这一天或这一月得到?
解决方案
细节
- 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))")
推荐阅读
- python - 如何删除在另一列中具有特定值的所有 NaN 值的行?
- amazon-athena - 从雅典娜的日期获取 YEARMONTH
- three.js - ThreeJS 点(点云)与使用自定义着色器材质的光照
- node.js - Firebase 电子邮件功能找不到用户
- mongodb - RESTful API、补丁、猫鼬更新命令不更新,而只是清除字段
- java - Spring Security:WebSecurityConfig 类 `antMatchers(...).permitAll()` 不起作用
- pine-script - 在 TradingView 中加载和加载字符串
- python-3.x - 当 AutomationFocusChangedEventHandler 在前台运行应用程序窗口时,如何阻止我的 Windows python 3 应用程序崩溃?
- javascript - 带有角度组件问题的引导下拉菜单
- c# - HBase 自定义地图归约器作业