Convert a NSDate to milliseconds epoch time - ios

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/

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.

How to compare time greater than 3 sec in ios

How to compare time is greater than 3 sec in ios.
Time is like "2016-05-10 05:31:14". I got code for comparing like greater or less with specific time but how i will achieve it is greater than 3 sec etc.
You can get seconds difference between two dates by
NSDate *someDate;//Some Date
NSLog(#"Seconds --> %f",[[NSDate date] timeIntervalSinceDate: someDate]);
Please try this one. May be Its possible for you:
NSDate* timeNow = [NSDate date];
// If less than 30 seconds, do something
if ([timeNow timeIntervalSinceDate:anEarlierTime] < 30.0f)
{
// Do something
}
- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
NSDate* enddate = checkEndDate;
NSDate* currentdate = [NSDate date];
NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
double secondsInMinute = 60;
// secondsBetweenDates is your seconds difference
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
if (secondsBetweenDates == 0)
return YES;
else if (secondsBetweenDates < 0)
return YES;
else
return NO;
}
Here, secondsBetweenDates is your difference in seconds. You can check that it is smaller or greater or equal than 3.
You can get difference here in hours also!
Hope this will help :)

NSTimeInterval in seconds between dates = nan

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);

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!

Resources