如何从JSON DarkSky swift获得一天

时间:2017-08-04 13:32:47

标签: ios iphone json swift nsdate

我想在我的天气应用程序中进行每周预测(星期日:星期一:等等......)所以我正在使用DarkSky,但我注意到了一些奇怪的东西。

"daily": {
"summary": "Light rain throughout the week, with temperatures bottoming out at 48°F on Sunday.",
"icon": "rain",
"data": [
  {
   -> "time": 1453363200, <-

没有值表示当天的名字,只有这个名为'time'的属性。我认为它代表秒,但我不知道如何获得请求的一天。就像我如何确定一个特定的日子?

3 个答案:

答案 0 :(得分:2)

另一个提供的答案是使用DateFormatter,它也将负责本地化,并且不需要放入DateComponents。

这取自游乐场

let date = Date(timeIntervalSince1970: 1453363200) // -> "Jan 21, 2016, 8:00 AM"
let formatter = DateFormatter()

formatter.dateFormat = "EEEE"

let day = formatter.string(from: date) // -> "Thursday"

如果您想查看其他日期格式字符串,您可以在http://nsdateformatter.com看到非常方便的参考。

一般情况下,尽管您希望避免对日期格式进行硬编码,以便呈现除此之外的简单输出。在这种情况下,设置日期格式化程序的dateStyletimeStyle属性是一种更好的方式,可以使用适合文化和语言环境的可见日期进行呈现。

答案 1 :(得分:1)

该值表示UNIX时间戳(自1970年1月1日起的秒数),您可以使用以下命令创建日期:

let date = Date(timeIntervalSince1970: 1453363200) // January 21, 2016 9:00 am

答案 2 :(得分:0)

首先将字符串转换为Date格式(来自vadian's answer):

let date = Date(timeIntervalSince1970: 1453363200)

然后您可以使用Calendar提取日期组件:

let components = Calendar.current.dateComponents([.weekday], from: date)
let weekday = components.weekday

dateComponents的第一个参数从Calendar.Component enum获取一系列元素。

例如,如果您想要小时,分钟,秒和工作日,您可以执行以下操作:

let components = Calendar.current.dateComponents([.hour, .minute, .second, .weekday], from: date)

let hour = components.hour
let minute = components.minute
let second = components.second
let weekday = components.weekday
// ...etc

更新

请注意,.weekday返回与星期几的索引相对应的整数(已本地化)。

如果您想要当天的实际名称(例如星期一,星期二等),则需要访问Calendar的{​​{1}}属性(也是本地化的)。

weekdaySymbols

let weekdayName = Calendar.current.weekdaySymbols[weekday ?? 0] 是可选的,因此我使用默认值weekday