iOS Core Motion how to convert timestamp to Date? - ios

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.

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.

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"

Related

dateComponents() from... to in days shows from now to tomorrow as 0 days?

I have datecomponent objects that represent some time in the future. I want to calculate how many dates from now until that date. I'm also including representation of the dates simply as dates. What I'm finding is that when I am trying to show how many there are to a date that is 'tomorrow' it's showing 0. To my mind it should be showing 1. I can try a hacky way of just adding 1 to my count but I'm wondering is it because it's trying to round to the nearest 24 hours or something? If so how can I 'fix' it?
Here is my sample code:
let myPreviousRelevantDate = self.datePickerOutlet.date
let nextDate = Date(timeInterval: Double(86400 * (myDurationInDaysAsInt)), since: myPreviousRelevantDate!)
let daysToNextDate = Calendar.current.dateComponents([.day], from: Date(), to: nextDate).day!
What I'd like to avoid is the number of days to the target date changing during the day also - i.e. regardless of the timestamp of my target date - the number of days to that day remaining constant until midnight is reached.
If your intent is to calculate the number of days using a timeless calendrical calculation what you need is to use noon time. Note that not every day has 24 hours, you should always use calendar method to add days to a date:
extension Date {
var noon: Date {
Calendar(identifier: .iso8601)
.date(
bySettingHour: 12,
minute: 0,
second: 0,
of: self
)!
}
}
let daysToNextDate = Calendar.current.dateComponents([.day], from: Date().noon, to: nextDate.noon).day!

convert date to specific timezone iOS swift [duplicate]

how can i return a NSDate in a predefined time zone from a string
let responseString = "2015-8-17 GMT+05:30"
var dFormatter = NSDateFormatter()
dFormatter.dateFormat = "yyyy-M-dd ZZZZ"
var serverTime = dFormatter.dateFromString(responseString)
println("NSDate : \(serverTime!)")
the above code returns the time as
2015-08-16 18:30:00 +0000
The date format has to be assigned to the dateFormat property of the date formatter instead.
let date = NSDate.date()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let str = dateFormatter.stringFromDate(date)
println(str)
This prints the date using the default time zone on the device. Only if you want the output according to a different time zone then you would add for example
Swift 3.*
dateFormatter.timeZone = NSTimeZone(name: "UTC")
Swift 4.*
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
also refer link http://www.brianjcoleman.com/tutorial-nsdate-in-swift/
how can i return a NSDate in a predefined time zone?
You can't.
An instance of NSDate does not carry any information about timezone or calendar. It just simply identifies one point in universal time.
You can interpret this NSDate object in whatever calendar you want. Swift's string interpolation (the last line of your example code) uses an NSDateFormatter that uses UTC (that's the "+0000" in the output).
If you want the NSDate's value as a string in the current user's calendar you have to explicitly set up a date formatter for that.
Swift 4.0
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
If you always have the same time zone for the input string, you can create two date formatters to output the local time zone (or a specified one):
let timeFormatterGet = DateFormatter()
timeFormatterGet.dateFormat = "h:mm a"
timeFormatterGet.timeZone = TimeZone(abbreviation: "PST")
let timeFormatterPrint = DateFormatter()
timeFormatterPrint.dateFormat = "h:mm a"
// timeFormatterPrint.timeZone = TimeZone(abbreviation: "EST") // if you want to specify timezone for output, otherwise leave this line blank and it will default to devices timezone
if let date = timeFormatterGet.date(from: "3:30 PM") {
print(timeFormatterPrint.string(from: date)). // "6:30 PM" if device in EST
} else {
print("There was an error decoding the string")
}
The number 1 means 1 regardless of language. Yet in English it's spelled as one, in Spanish it's una, in Arabic it wahid, etc.
Similarly 123982373 seconds pass 1970 is going to reflect differently in different timezones or calendar formats, but's all still 123982373 seconds passed 1970
The difference between 3 seconds and 7 seconds is 4 seconds. That doesn't require a calendar. Neither you need a calendar/timezone to know the difference in time between these two Epoch times 1585420200 and 1584729000
Dates are just a timeInterval from January 1, 1970 (midnight UTC/GMT). Dates also happen to have a string representation.
Repeating Nikolia's answer, Swift's default string interpolation (2015-08-16 18:30:00 +0000) uses a DateFormatter that uses UTC (that's the "+0000" in the output).
Calendars with the use of timezones give us a contextual representation that is just easier to understand than trying to calculate the difference between two gigantic numbers.
Meaning a single date (think of a single timeInterval since 1970) will have a different string interpretations per calendar. On top of that a calendar will itself vary based on time zones
I highly recommend that you go and play around with this Epoch converter site and see how selecting a different timezone will cause the string representations for the same moment/date/timeInterval to change
I also recommend to see this answer. Mainly this part:
Timezone is just an amendment to the timestamp string, it's not considered by the date formatter.
To consider the time zone you have to set the timeZone of the formatter
dateFormatter.timeZone = TimeZone(secondsFromGMT: -14400)

DateComponents giving wrong date

I am trying to convert today's date using DateComponents:
let calendar = Calendar.current
//add today's date
var todayDate = Date()
var dateComponents = calendar.dateComponents([.day, .month, .year], from: todayDate)
dateComponents.timeZone = TimeZone.current
todayDate = calendar.date(from: dateComponents)!
While debugging I found that after declaring todayDate, its value was 2016-11-11 07:44:44 +0000. After using dateComponents, the value changed to 2016-11-10 18:30:00 +0000. Whereas according to my location, the day should be 11th November, and the time should be somewhere between 1 or 2 PM. Why is this happening?
You haven't specified a timezone, nor hours minutes and seconds in your components. So, all these values are assumed to be zero. The resulting time is at midnight GMT on the year, month and day that you specified.
When you printed the result, you specified your current timezone, which appears to be 5h 30m different.
I'm guessing you are in India.

ios Swift - trouble setting time with seconds at zero [duplicate]

I have a date picker that returns me a NSdate value. And I want to have a date value of seconds set to 0. I have the code to do it in objective c as
NSTimeInterval time = floor([date timeIntervalSinceReferenceDate] / 60.0) * 60.0;
return [NSDate dateWithTimeIntervalSinceReferenceDate:time];
where date is the datepicker's date. So how to realise this in swift?
It is almost identical in Swift:
let date = NSDate()
let ti = floor(date.timeIntervalSinceReferenceDate/60.0) * 60.0
let date1 = NSDate(timeIntervalSinceReferenceDate: ti)
The same can be achieved with NSCalendar methods:
let cal = NSCalendar.currentCalendar()
var date2 : NSDate?
cal.rangeOfUnit(.Minute, startDate: &date2, interval: nil, forDate: date)
and this has the great advantage that it can easily be adapted for
larger time units like days, months, etc. which do not have a fixed
length (e.g. a day can have 23, 24, or 25 hours in regions with
daylight saving time).

where is timeIntervalSince1970 property in swift

I am trying to get the current milliseconds and according to all the questions on Google, i should use timeIntervalSince1970 property of NSDate
however i already did this:
var startTime = NSData()
and then
startTime. timeIntervalSince1970
and
startTime. timeIntervalSince1970()
but it seems there is no property anymore, right?
if yes, what is the replacement please?
The error is: NSDate not NSData.
Also there should not be space after the "."?
var startTime = NSDate()
let interval = startTime.timeIntervalSince1970
From Apple docs:
var timeIntervalSince1970: NSTimeInterval { get }
This property’s value is negative if the date object is earlier than January 1, 1970 at 12:00 a.m. GMT.

Resources