如何从日期类型获取日期和月份-Swift 4 [英] How to get day and month from Date type - swift 4

查看:133
本文介绍了如何从日期类型获取日期和月份-Swift 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have variable with data type Date, where I have stored date in this format


2018-12-24 18:00: 00 UTC

2018-12-24 18:00:00 UTC

如何从这一天或这一天开始?

How can I get from this day or month?

推荐答案

详细信息




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

  • 如何将字符串转换为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)
        }
    }
    



    用法



    Usage

    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 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆