0

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?

SwiftyJD
  • 5,257
  • 7
  • 41
  • 92
  • For how to get a `Date` from unix timestamp: https://developer.apple.com/documentation/foundation/date/1780353-init – keji Feb 16 '19 at 21:45

2 Answers2

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"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
0

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.

qtngo
  • 1,594
  • 1
  • 11
  • 13