How to get the day based on a time field (seconds since midnight 1970)?

◇◆丶佛笑我妖孽 提交于 2020-01-11 13:16:17

问题


I'm grabbing data from an api, and one of the values I'm getting is for day of the week, the data returned from api looks like this:

"time": 1550376000

I created this function to get the date:

  func getDate(value: Int) -> String {
        let date = Calendar.current.date(byAdding: .day, value: value, to: Date())
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "E"

        return dateFormatter.string(from: date!)
    }

but was told there is a much safer way to get it instead of assuming we get consecutive days starting with today. Does anyone know how to build a date out of the time field (it is seconds since midnight 1970) and then use Calendar and DateComponent to figure out the day?


回答1:


Looks like you are receiving json data so you should structure your data and conform to Decodable protocol to convert your data to an object properly structured.

struct Object: Decodable {
    let time: Date
}

Don't forget to set the decoder dateDecodingStrategy property to secondsSince1970

do {
    let obj = try decoder.decode(Object.self, from: Data(json.utf8))
    let date = obj.time   // "Feb 17, 2019 at 1:00 AM"
    print(date.description(with: .current))// "Sunday, February 17, 2019 at 1:00:00 AM Brasilia Standard Time\n"
} catch {
    print(error)
}

Then you just need to get the weekday component (1...7 = Sun...Sat) and get the calendar shortWeekdaySymbols (localised), subtract 1 from the component value and use it as index to get correspondent symbol. Same approach I used in this post How to print name of the day of the week? to get the full week day name:

extension Date {
    var weekDay: Int {
        return Calendar.current.component(.weekday, from: self)
    }
    var weekdaySymbolShort: String {
        return Calendar.current.shortWeekdaySymbols[weekDay-1]
    }
}

print(date.weekdaySymbolShort)   // "Sun\n"



回答2:


You can use Calendar to get date component from the Date:

let date = Date(timeIntervalSince1970: time)// time is your value 1550376000
let timeComponents = Calendar.current.dateComponents([.weekday, .day, .month, .year], from: date)
print("\(timeComponents.weekday) \(timeComponents.day!) \(timeComponents.month!) \(timeComponents.year!)") // print "7 16 2 2019"
print("\(\(Calendar.current.shortWeekdaySymbols[timeComponents.weekday!-1]))") // print "Sat"

Hope this helps.



来源:https://stackoverflow.com/questions/54727924/how-to-get-the-day-based-on-a-time-field-seconds-since-midnight-1970

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