How to get day and month from Date type - swift 4

耗尽温柔 提交于 2020-05-17 05:45:19

问题


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

2018-12-24 18:00:00 UTC

How can I get from this day or month?


回答1:


If you saved "2018-12-24 18:00:00 UTC" as a String, you can try this:

    let dateString = "2018-12-24 18:00:00 UTC"
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss 'UTC'"
    guard let date = formatter.date(from: dateString) else {
        return
    }

    formatter.dateFormat = "yyyy"
    let year = formatter.string(from: date)
    formatter.dateFormat = "MM"
    let month = formatter.string(from: date)
    formatter.dateFormat = "dd"
    let day = formatter.string(from: date)
    print(year, month, day) // 2018 12 24

Best Wishes!




回答2:


Details

  • Xcode Version 11.0 (11A420a), Swift 5

Links

How to convert string to Date

Solution

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))")



回答3:


Is that String or Date type?

if it is date you can do so:

 let calanderDate = Calendar.current.dateComponents([.day, .year, .month], from: date)

that will give you the day, year and month




回答4:


The date string is not ISO8601 compliant, nevertheless you can use ISO8601DateFormatter if you replace <space> + UTC with Z and use custom format options.

Create a Date from the string and get the DateComponents for day and month

let string = "2018-12-24 18:00:00 UTC"

let formatter = ISO8601DateFormatter()
let trimmedString = string.replacingOccurrences(of: "\\s?UTC", with: "Z", options: .regularExpression)
formatter.formatOptions = [.withFullDate, .withFullTime, .withSpaceBetweenDateAndTime]
if let date = formatter.date(from: trimmedString) {
    let components = Calendar.current.dateComponents([.day, .month], from: date)
    let day = components.day!
    let month = components.month!
    print(day, month)
}


来源:https://stackoverflow.com/questions/53356392/how-to-get-day-and-month-from-date-type-swift-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!