4

I'm examining CMRecordedAccelerometerData and it has a timestamp, defined as:

The timestamp is the amount of time in seconds since the device booted.

How do I convert timestamp from device last boot to NSDate?

For example, the system provides a CMRecordedAccelerometerData object with a timestamp value of: 1030958.895134

If I use any of the available reference frames (1970, reference date), I will get a wrong date, not in 2019. I want the real date when the event was recorded.

enter image description here

Alex Stone
  • 46,408
  • 55
  • 231
  • 407
  • Possible duplicate of [Using DateFormatter on a Unix timestamp](https://stackoverflow.com/questions/40648284/using-dateformatter-on-a-unix-timestamp) – Prashant Tukadiya Nov 25 '19 at 05:40
  • simply `let date = Date(timeIntervalSince1970: timeStampHere)` ? – Prashant Tukadiya Nov 25 '19 at 05:41
  • 1
    Please read the question again, the system returns an arbitrary number of seconds since last boot. If I use your solution, I will get a date in the 1970, not in 2019. I want the real date when the event was recorded – Alex Stone Nov 29 '19 at 07:51
  • @AlexStone My answer should get you the date of the timestamp. Did it not work for you? – akaur Dec 11 '19 at 17:30
  • 1
    @akaur I still don't know how to get the timestamp of the last boot, so the answer does not work :( – Alex Stone Dec 14 '19 at 15:54

2 Answers2

2

This answer comes a bit late I guess, but, first, you can get the boot time by subtracting the uptime ProcessInfo.processInfo.systemUptime from now, but otherwise from iOS 9+ ProcessInfo.processInfo.systemUptime has the date property startDate, which should be what you were after in the first place.

Ecuador
  • 1,014
  • 9
  • 26
-3

The timestamp is a TimeInterval, a typealias for Double that represents duration as a number of seconds. So you can convert TimeInterval to a Date by using NSDate's (timeIntervalSince1970:).

let myTimeInterval:TimeInterval = 1574660642
let dateNow = NSDate(timeIntervalSince1970: myTimeInterval)  //will print "Nov 24, 2019 at 9:44 PM"

If you need to the date relative to the current date with the TimeInterval, you can use (timeInterval:since:).

var date = Date()
let timestampOfLastBoot: TimeInterval = 1572628813
let currentTimestamp: TimeInterval = NSDate().timeIntervalSince1970
let dateOfTimeStamp = Date(timeInterval: timestampOfLastBoot-currentTimestamp, since: date)    //will print "Nov 1, 2019 at 10:20 AM"
akaur
  • 365
  • 1
  • 5