如何根据时间字段(1970年午夜以来的秒数)获得一天?

问题描述 投票:0回答:2

我正在从api中获取数据,我得到的一个值是一周中的某天,从api返回的数据如下所示:

"time": 1550376000

我创建了这个函数来获取日期:

  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来计算出这一天?

ios swift nscalendar
2个回答
1
投票

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

struct Object: Decodable {
    let time: Date
}

不要忘记将解码器dateDecodingStrategy属性设置为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 =太阳...星期六)并获得日历shortWeekdaySymbols(本地化),从组件值中减去1并将其用作索引以获取对应的符号。我在这篇文章中用How to print name of the day of the week?获得完整的工作日名称的方法相同:

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"

0
投票

你可以使用CalendarDate获取日期组件:

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"

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.