NSTimeInterval in seconds between dates = nan - ios

NSTimeInterval executionTime = [self.EndDownloadTime timeIntervalSinceDate:self.StartDownloadTime];
NSLog(#"Execution Time: %f", executionTime);
Result is always "nan". When i switch EndDownloadTime and StartDownloadTime, time is "0.00000"
StartDownloadTime and EndDownloadTime are types of NSDate.
How do i get the seconds between the two dates?
Thank you in advance.

The simplest solution is a better method, check the docs when things seem complicated:
NSTimeInterval executionTime = [self.EndDownloadTime timeIntervalSinceDate:self.StartDownloadTime];
When you are debugging a problem and everything looks correct but the code is failing then an assumption must be wrong. There are two assumptions here (at least): the values of self.EndDownloadTime and self.StartDownloadTime. NSLog them or use the debugger examining the values as you step through.
Check everything:
NSLog(#"StartDownloadTime: %#", self.StartDownloadTime);
NSLog(#"StartloadTimeInterval: %f", [self.StartDownloadTime timeIntervalSince1970]);
NSLog(#"EndDownloadTime: %#", self.EndDownloadTime);
NSLog(#"EndDownloadTimeInterval: %f", [self.EndDownloadTime timeIntervalSince1970]);
NSTimeInterval executionTime = [self.EndDownloadTime timeIntervalSince1970] - [self.StartDownloadTime timeIntervalSince1970];
NSLog(#"Execution Time: %f", executionTime);
Note: In Cocoa* properties and variables and method names by convention begin with a lower case letter, class names with an uppercase letter. This makes it easier for others to understand your code.

Your code looks right. Try this and print value of variables to know if the two dates are correct.
NSTimeInterval executionTime = [self.EndDownloadTime timeIntervalSince1970] - [self.StartDownloadTime timeIntervalSince1970];
NSLog(#"Execution Time: %f", executionTime);

Related

`[[NSDate date] timeIntervalSince1970]` in (C) free function always returns same value

If I have:
double now_ms() {
return 1000 * (float)[[NSDate date] timeIntervalSince1970];
};
:
NSLog( #"%f", now_ms() ); // inside a CADisplayLink tick-event
It gives the same value each time.
I can fix this by making a Lambda:
double (^now_ms)(void) = ^() {
return 1000.f * [[NSDate date] timeIntervalSince1970];
};
NSLog( #"%f", now_ms() ); // works!
However I would prefer it to be a free function.
What is going on?
I suspect this is some kind of run-time optimisation.
The issue is that NSTimeInterval (which is what timeIntervalSince1970 returns) is a double and you’re casting it to a float. But float can only capture roughly 7 significant digits. That’s not nearly accurate enough to capture the number of seconds since 1970, much less the number of milliseconds.
Your lambda solution works simply because you removed the float cast. You can do the same with your function:
double now_ms() {
return 1000.0 * [[NSDate date] timeIntervalSince1970];
}

How to get int value of time stamp which includes milliseconds in objective c

NSNumber * uniqueId = [NSNumber numberWithInt:([[NSDate date] timeIntervalSince1970])];
Milliseconds is not included in the above code.If i used like below code ,it is printing negative values.
NSNumber * uniqueId1 = [NSNumber numberWithInt:([[NSDate date] timeIntervalSince1970] * 1000)];
Can we get time stamp with milliseconds as int????
#AnjaniG you can use one of them..
NSString *strTimeStamp = [NSString stringWithFormat:#"%f",[[NSDate date] timeIntervalSince1970] * 1000];
int timestamps = [strTimeStamp intValue];
NSLog(#"number int = %d",timestamps);
You should not use an Int, [[NSDate date] timeIntervalSince1970] * 1000 is bigger than INT_MAX. You should use long long to store the value.
NSNumber * uniqueId1 = [NSNumber numberWithLongLong:([[NSDate date] timeIntervalSince1970] * 1000)];
The problem is that you are casting a floating point to an integer.
As per the documentation, timeIntervalSince1970 returns an NSTimeInterval, which is a double, not an integer.
In your first code example, you're actually discarding the milliseconds by casting.
In your second code example, you are overflowing the integer. After multiplying the value by 1000, it is too large to fit in an integer.
In the end, you're just doing too much code and you shouldn't need to really worry about this.
NSTimeInterval interval = [NSDate date].timeIntervalSince1970;
NSNumber *timestamp = #(interval * 1000.);
Here, I use the proper documented type of NSTimeInterval. Then I multiply that by 1,000 to change seconds to milliseconds. Finally, I use Clang literal syntax to instruct the compiler to create the appropriate NSNumber.

iOS - Comparing NSDate with another NSDate

i know how to get difference between two NSDate as follow
NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:anyPreviousDate];
and i know it will return me NSTimeInterval in positive seconds. what I want to know is what it will return if my anyPreviousDate is greater than [NSDate date] i.e. anyPreviousDate has not been passed it will come in future.
just curious if anybody has done that before.
Thanks in advance.
I have found another very nice approach to do the same...
here is the code, i thought to share it with stackoverflow.
Cocoa has couple of methods for this:
in NSDate
– isEqualToDate:
– earlierDate:
– laterDate:
– compare:
When you use - (NSComparisonResult)compare:(NSDate *)anotherDate ,you get back one of these:
The receiver and anotherDate are exactly equal to each other, NSOrderedSame
The receiver is later in time than anotherDate, NSOrderedDescending
The receiver is earlier in time than anotherDate, NSOrderedAscending.
example:
NSDate * now = [NSDate date];
NSDate * mile = [[NSDate alloc] initWithString:#"2001-03-24 10:45:32 +0600"];
NSComparisonResult result = [now compare:mile];
NSLog(#"%#", now);
NSLog(#"%#", mile);
switch (result)
{
case NSOrderedAscending: NSLog(#"%# is in future from %#", mile, now); break;
case NSOrderedDescending: NSLog(#"%# is in past from %#", mile, now); break;
case NSOrderedSame: NSLog(#"%# is the same as %#", mile, now); break;
default: NSLog(#"erorr dates %#, %#", mile, now); break;
}
[mile release];
if([previousDate compare:[NSDate date]] == NSOrderedDescending){
// Previous date is greater than current date.i.e. previous date
//is still to come
}else{
//Previous date is smaller then current date.i.e. previous date
//has passed.
}
compare method of NSDate object returns NSComparisonResult, which is an enum.
NSComparisonResult has following values.
NSOrderedSame is returned if left and right operands are equal
NSOrderedAscending is returned if left operand is smaller than the right operand
NSOrderedDescending is returned if ft operand is greater than the right operand
If anyPreviousDate is actually ten seconds in the future, then your code will return -10.0. It happens quite often that you define NSDates that are some time in the future (for example to do something one minute from now), so this isn't unusual at all.
this's a screenshot to see
NSDate * savedDate = [recordsDic[record.transactionId] modifiedDate];
NSDate * newDate = record.modifiedDate;
NSComparisonResult comparisonResult = [newDate compare:savedDate];
NSTimeInterval timeInterval = [newDate timeIntervalSinceDate:savedDate];
NSLog(#"\nsavedDate: %# \nnewDate : %# \n===> timeInterval: %f",savedDate,newDate,timeInterval);
if (comparisonResult == NSOrderedSame) {
NSLog(#"they are same!!!!");
} else {
NSLog(#"they are NOT same!!!!");
}
Console log:
2019-04-11 17:26:47.903059+0800 xxxxx[19268:24419134]
savedDate: Thu Apr 11 15:47:23 2019
newDate : Thu Apr 11 15:47:23 2019
===> timeInterval: 0.000365
2019-04-11 17:26:47.903193+0800 xxxxx[19268:24419134] they are NOT same!!!!
Can you believe this!? but That's true, I spent almost a whole day figuring this out. cause this won't consistently happen!!!
so I strongly recommend:
1. Do NOT use instance method "- (NSComparisonResult)compare:(NSDate *)other;" to compare, you would see something really wired and you can not figure out.
2. timeIntervalSinceDate is more precise.

How can I get the fileCreationDate to an accuracy of 6 decimal places when converted using timeIntervalSince1970?

How can I get the fileCreationDate for a file stored in the NSDocumentsDirectory to an accuracy of 6 decimal places when converted to an NSTimeInverval?
Some code:
//Not accurate enough:
NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:myPhotoPath error:nil];
NSDate *creationDateOfPhoto = [fileAttribs fileCreationDate];
NSTimeInterval creationDateAsTimeInterval = [creationDateOfPhoto timeIntervalSince1970];
NSLog(#"Creation Date of Photo As Time Interval Since 1970: %f", creationDateAsTimeInterval);
//With the desired accuracy:
NSDate* now = [NSDate date];
NSTimeInterval nowStampAsTimeInterval = [now timeIntervalSince1970];
NSLog(#"Now As Time Interval Since 1970: %f", nowStampAsTimeInterval);
A sample output from this code is:
Creation Date of Photo As Time Interval Since 1970: 1373022866.000000
Now As Time Interval Since 1970: 1373022884.294028
Is it possible or is it a limitation of storage in NSDocuments?
It's a OS level limitation. HFS+, the file system which is used by iOS, has a date resolution of one second - this is why all your file timestamps are whole seconds. Sub second precision isn't supported. Sorry!

Convert a NSDate to milliseconds epoch time

I need to be able to convert a date to a time stamp, an epoch in milliseconds.
All I see online are for converting milliseconds to NSDate and not the other way round. Any help out there?
NSTimeInterval is a double that already contains sub-second data after the decimal point. Depending what you need, your conversion could be a simple as multiplying by 1000.
- (void)testDateFormat
{
NSDate *date = [NSDate date];
NSLog(#"Time: %f", floor([date timeIntervalSince1970] * 1000));
NSLog(#"Time: %f", floor([date timeIntervalSince1970]));
NSLog(#"Time: %lli", [#(floor([date timeIntervalSince1970] * 1000)) longLongValue]);
NSLog(#"Time: %lli", [#(floor([date timeIntervalSince1970])) longLongValue]);
}
// Result
// 2013-04-15 13:28:11.284 TestApp[10469:907] Time: 1366057691284.000000
// 2013-04-15 13:28:11.286 TestApp[10469:907] Time: 1366057691.000000
// 2013-04-15 13:28:11.287 TestApp[10469:907] Time: 1366057691284
// 2013-04-15 13:28:11.288 TestApp[10469:907] Time: 1366057691
timeIntervalSince1970 will return seconds from 1970. There are other timeIntervalSince methods if needed.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/timeIntervalSince1970
timeIntervalSince1970 multiply the return value by 1000
because the returned value is in second not in millisecond
kindly check that website for more testing http://currentmillis.com/

Resources