Nslog timestamp - iphone

I want to nslog the device motion timestamp property .
The device motion is in the class CMMotionManager.devicemotion.timestamp
Any ideas.

Here the solution I put in place because the date is according to Apple documentation :
The time stamp is the amount of time in seconds since the phone booted.
I first save the originDate at the first mesure (if my NSDate is nil).
[self.motionManager startGyroUpdatesToQueue:self.queue withHandler:^(CMGyroData *gyroData, NSError *error) {
if (self.originDate == nil) {
self.originDate = [NSDate dateWithTimeIntervalSinceNow:-gyroData.timestamp];
}
}];
Then I can display when I want the real date like this :
[NSDate dateWithTimeInterval:mygyroData.timestamp sinceDate:self.originDate]
Don't forget to reset the originDate to nil if you need to restart some mesure.

Edit: Please see Nicolas Lauquin's answer. Per the comments, the following solution is not correct but is retained here for history (and because I can't delete it since it is currently marked accepted).
The timestamp property is an NSTimeInterval, so you should be able to do:
NSLog(#"Motion at time: %#",
[NSDate dateWithTimeIntervalSinceReferenceDate:devicemotion.timestamp]);
NSTimeInterval is just a typedef'd double type, so you could use %f instead of %# and log it directly.
Also, the docs don't indicate whether this timestamp is set against Apple's reference date or the standard *nix date, so you may need to use [NSDate dateWithTimeIntervalSince1970:] if the aforementioned method returns dates far in the future.
As #davidbitton has suggested the CMDeviceMotion's timestamp is relative to the last device boot, the correct NSDate could be derived by
NSDate *startupTime = [NSDate dateWithTimeIntervalSinceNow:
-1 * [[NSProcessInfo processInfo] systemUptime]];
NSDate *deviceMotionDate = [NSDate dateWithTimeInterval:devicemotion.timestamp
sinceDate:startupTime];
This should yield a roughly accurate NSDate object, assuming #davidbitton is correct. (reference: NSProcessInfo -systemUptime)
However, given how complicated this is, I would now suggest for simplicity that, given the nature of the timestamp property, that you log it in a format string as something like
"... event logged at %0.2f seconds since startup...", devicemotion.timestamp

Related

Comparing NSDate to [NSDate date] Fastest Way?

I have a core data table view and I am comparing dates. The method which I currently use is: if ([todayDate compare: [NSDate date]]==NSOrderedAscending) . This works perfectly but slow. I do not need to know the difference in time though. Any help is much appreciated!
I really think, that NSDates method isEqualToDate: is what you are searching for. Seems to me to be the Apple-way to answer your question:
NSDate *date1 = ...;
NSDate *date2 = ...;
BOOL datesAreEqual = [date1 isEqualToDate:date2];
For more information visit https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsdate_Class/Reference/Reference.html
One option could be to not actually create a new NSDate object but use the time interval for comparison. Don't know about the performance, but it might be worth a try.
if ([todayDate timeIntervalSinceReferenceDate] > [NSDate timeIntervalSinceReferenceDate]) {
...
}
You should remember the current date or current timestamp in a local variable:
NSTimeInterval current = [NSDate timeIntervalSinceReferenceDate];
And use this value later for all your comparisons:
myTimestamp = [myDate timeIntervalSinceReferenceDate]
if (myTimestamp == current) {
return NSOrderedSame;
} else if (myTimestamp > current) {
return NSOrderedDescending;
} else {
return NSOrderedAscending;
}
Or a faster way, using C functions:
// Get the current calendar time as a time_t object.
time_t time ( time_t * timer );
// Return difference between two times
double difftime ( time_t time2, time_t time1 );
I've not measured it, but you may want to try:
NSTimeInterval i = [todayDate timeIntervalSinceNow];
where the result (i) may be positive or negative.
You might also try CFDateCompare.
Or you might want to consider another way to represent a point in time in your database -- such as a CFTimeInterval (a double representing the number of seconds from a common reference time).

How can validate NSDATE

How to find one text field value is within past 60 day excluding current date.
For example if I enter value in text field is 20-July-2012 using Date Picker.Then I click submit,it'll check that specific is date is within 60 days or not. If the values are entered which is before 60 days an alert message is displayed. The values are retrieved from api.
NSDate *today = [NSDate date];
NSTimeInterval dateTime;
if ([pickerDate isEqualToDate:today]) //pickerDate is a NSDate
{
NSLog (#"Dates are equal");
}
dateTime = ([pickerDate timeIntervalSinceDate:today] / 86400);
if(dateTime < 0) //Check if visit date is a past date, dateTime returns - val
{
NSLog (#"Past Date");
}
else
{
NSLog (#"Future Date");
}
Change the value of 86400 to suit your query.In this case, it is the number of seconds we want to compare.
First, convert the text into an NSDate. Then use
timeIntervalSinceDate:[NSDate dateWithTimeIntervalSinceNow:0]
There are a couple of ways to convert text into an NSDate. You can format the text correctly and then use dateWithString or you can convert everything into numbers, multiply them out, and one of the dateWithTimeInterval methods.
If you want the user to be able to enter "July" (plain text month) then you might want to write a method that converts months into their numerical equivalents with string matching.
NSDate *lastDate; //your date I hope you have created it
NSDate *todaysDate = [NSDate date];
NSTimeInterval lastDiff = [lastDate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [todaysDate timeIntervalSinceNow];
NSTimeInterval dateDiff = lastDiff - todaysDiff; // number of seconds
int days = dateDiff/(60*60*24); // 5.8 would become 5 as I'm taking int
How do you define 60 days?
You may want to use NSCalendar -dateByAddingComponents:toDate:options: to ensure your 60 days really are 60 days.
NSCalendar also provides -components:fromDate: and -dateFromComponents: which are very nice when dealing with date components.
If 60 days do not need to be true calendar days (daylight saving time switches, astronomical time corrections, stuff like that), you can just have fun with NSDate and the time interval methods alone.

Not able to set NSTimeZone to a required format

I have a TimeZone as NSString value given as "GMT-09:00".
All I want is to setup my NSTimeZone with this format. I tried but wasn't able to do this. This time may vary every time so i can't set it as static in the method
eg. i can't do this -- timeZoneForSecondsFromGMT:(-9*3600).
Also, can I convert the above format (GMT-09:00) into number of seconds anyhow??
EDIT : I just want to set the time zone to a specific GMT format. It could be anything, GMT-09:00, GMT+05:30, etc.
If it was a static value I could have used the below method for NSTimeZone.
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:(-9*3600)]];
But the value "GMT-09:00" is an NSString. So everytime, I would have to break the string and get the values for Hours and minutes. Is there an easier way?????
Thanks for the help!
have you tried something like this?
NSString *tzStr = #"GMT-09:00";
NSTimeZone *tz = [[NSTimeZone alloc] initWithName:tzStr];
NSLog(#"Tz: %#", tz);
NSLog(#"Offset: %d", [tz secondsFromGMT]);
// Tz: GMT-0900 (GMT-09:00) offset -32400
// Offset: -32400
works with #"GMT+5:30" too.
// Tz: GMT+0530 (GMT+05:30) offset 19800
and then just use [formatter setTimeZone:tz];
this one is helpful to you. optimized help
float offsetSecond = ([[NSTimeZone systemTimeZone] secondsFromGMT] / 3600.0);

finding NSDate's in an NSArray that have a time of day after a given time (e.g. 8pm)?

Is there a quick way in Objective-C of identifying NSDate's in an NSArray that have a time of day after a given time (e.g. 8pm)?
I can't quite see anyway other than manually walking through each NSDate in the array and then using NSDateComponents to break out the hour/minute/second...Not even sure if there is a simple way to get the time from an NSDate in a fashion that represents a fraction of 24hours, as this might help a little. (e.g. 6pm would be 18/24 = 0.75 in this case)
There is no need to break in NSDateComponents.
NSTimeInterval interval = [date1 timeIntervalSinceDate:date2];
if (interval > 0) {
// date2 is earlier
} else {
// date1 is earlier
}
Now you can represent your target time(8 P.M., for example) with date2 and compare all dates of array with that.
Haven't tried this myself, but I guess
- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate
is what you're looking for.

Best way to store a 'time' value

My class needs two properties: startTime and endTime. What is the best class to use? I know there is NSDate, but I only need to store a specific time (something in between 00:00-23:59), I don't need a date. What is the most elegant solution here?
NSTimeInterval is probably good enough for this.
It stores a time value in seconds as a double.
Eg. 5 mins = 300.0
I believe the most elegant solution, and what you want, is NSTimeInterval, that is the primitive type that NSDate is built on top.
NSTimeInterval is a typedef for double, and is a measurement of time in seconds. This primitive time type do not have any concept of a reference date. What NSDate do is to add this concept of reference date and anchor the 0.0 time at 1 January 2001 GMT. There is nothing that stops you from inventing your own reference date or anchor, like for example "midnight of whatever day there is".
What you can do is to add two properties of the NSTimeInterval either as startTime and endTime and let them both use midnight as the reference. Or you could skip endTime and go for a startTime and duration combo.
There's NSDateComponents, which "can also be used to specify a duration of time, for example, 5 hours and 16 minutes."
The NSDate class is similar to the DateTime class in C#: both hold a date and time, but they can be independent of each other. In Cocoa, you would compare two NSDate classes:
//Create NSDate objects in the time format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSString *startTimeString = #"00:00:00"; //0 seconds
NSString *endTimeString = #"00:00:52"; //52 seconds
NSDate *startTime = [dateFormatter dateFromString:startTimeString];
NSDate *endTime = [dateFormatter dateFromString:endTimeString];
//Compare the time
BOOL date1before2 = [startTime compare:endTime] == NSOrderedAscending;