本文介绍了如何基于时间字段(自1970年午夜以来的秒数)获取日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从api中获取数据,而我获取的值之一是星期几,从api返回的数据如下所示:

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!)
    }

但是被告知有一种更安全的方法来获得它,而不是假设我们从今天开始连续几天.有谁知道如何根据时间字段(自1970年午夜以来的秒数)构建日期,然后使用Calendar和DateComponent确定日期?

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?

推荐答案

看起来您正在接收json数据,因此您应该对数据进行结构化并遵守Decodable协议,以将数据转换为结构正确的对象.

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
}

别忘了将解码器dateDecodingStrategy属性设置为secondsSince1970

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

然后,您只需要获取工作日组件(1 ... 7 = Sun ... Sat)并获取日历shortWeekdaySymbols(已本地化),从组件值中减去1并将其用作索引以获取对应的符号.我在这篇文章中使用的相同方法如何打印星期几的名称?以获取完整的星期几名称:

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"

这篇关于如何基于时间字段(自1970年午夜以来的秒数)获取日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 09:47