Get Epoch Time From Date - objective-c

I am trying to get the epoch time for a date (2016-03-31T17:58:30.812Z) and I'm having trouble converting. Here is what I have tried:
NSDateFormatter* df = [NSDateFormatter new];
NSDate* tokenCreated = [NSDate new];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:sssZ"];
tokenCreated = [df dateFromString:#"2016-03-31T17:58:30.812Z"];
NSTimeInterval timeTokenCreated = [tokenCreated timeIntervalSince1970];
NSLog(#"TIME TOKEN::::%f", timeTokenCreated);
What is happening is that tokenCreated is being set to nil, and I'm unable to convert. Can someone please point me in the right direction and tell me where I'm going wrong?

What is happening is that tokenCreated is being set to nil
Because your date format doesn't match your string. For example, your format fails to distinguish between the seconds and the fractional seconds. You would need this:
#"yyyy-MM-dd'T'HH:mm:ss.SSSZ"

Related

Getting NSDate from time string with UTC format

I am trying to get a NSDate object from a UTC time string. The example of the time string is this:
2016-07-29T11:43:55+02:00
I am usingNSDateFormatter and set the formate as: yyyy-MM-dd'T'HH:mm:ss
However this gives me the take with incorrect time zone. So the above date will be: 2016-07-29T09:43:55+00:00
How do I keep the time zone aspect as well?
I did try adding a 'Z' to the end of the formatter but that just returns a nil date.
Try this
NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
[userFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[userFormatter setLocale:posix];
NSString *dateConverted = [userFormatter stringFromDate:theDate];
Thanks to all that help. Solved the issue. The time on my iOS Simulator was correct. However when I called [NSDate date]; it show'd me a time two hours before local time. Hence the 'errors' I was seeing in the formatting of NSDate.
Use NSISO8601DateFormatter if targeting iOS 10 and above. https://developer.apple.com/documentation/foundation/nsiso8601dateformatter

How to get the millisecond part of current time?

I'm trying to record an event at its happening time by accuracy of milliseconds. Below is my code:
NSDate * now = [NSDate date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"HH:mm:ss.SSS"];
NSString *timeString = [outputFormatter stringFromDate:now];
However, the results are as this:
45:11.3
It looks like time record has been rounded to 0.1 second, while all the second and third decimal accuracy is lost. Can anyone suggest where the problem is and how I can get the millisecond information?
Thank you all!
Paul
Your code works fine for me. Here it is (in Swift):
let f = NSDateFormatter()
f.dateFormat = "HH:mm:ss.SSS"
let timeString = f.stringFromDate(NSDate()) // "20:26:19.118"
You do not show the code by which you read the resulting timeString but perhaps the fault lies in how you are doing that. It is odd that the Hour part is missing from your output too.

parsing date from string, nsdate, objective c

Below is a string represented a date
NSString *dateStr = #"2011-07-06";
And when I am trying to convert it to NSDate by doing :
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd"];
NSDate *tmp = [format dateFromString:dateStr];
NSLog(#"tmp is %#",[tmp description]);
What I am getting from the console is
tmp is 2011-07-06 04:00:00 +0000
I dont understand why I am getting extra info :04:00:00 +0000 for the result
Please help if you experienced it before
Your code
NSString *dateStr = #"2011-07-06";
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd"];
NSDate *tmp = [format dateFromString:dateStr]
will result in a NSDate object, that represents your local time at 0:00 — the beginning of the day.
but if you print a plain date object, it will result in a string that represents the time in GMT timezone, as internally all dates are normalized to that timezone.
As your string is 4 hours ahead, we can tell, that you most likely are in East Europe, maybe Moscow.
So if you want to see the string in your timezone, you need to use a NSDateFormatter to create it from the date object.
NSLog(#"tmp is %#",[formatter stringFromDate:tmp]);
to check, if it is correct, what I said, change the format to contain the time components.
formatter.format = [#"yyyy-MM-dd HH:mm"];
NSLog(#"tmp is %#",[formatter stringFromDate:tmp]);
The formatter will also take "oddities" like Leap Day, Leap Month (yes — those exits), Daylight Saving Times, Leap Seconds … in account — accordantly to the current calendar.
A great WWDC 2011 Video: Performing Calendar Calculations — a must-see for every cocoa developer.
BTW: to print a object with NSLog you dont need to call -description on it to pass in a string. NSLog will do this internally.
NSLog(#"tmp is %#", tmp);
is just fine.
The answer is simple, NSLog just converts the NSDate to a NSString, using its formatter with GMT (zero) timezone.
Your formatter is by default set to your default time zone, which is probably -4:00. When you print it out, NSLog converts it to 0:00, adding 4 hours.
In general, it's unsafe to parse dates without specifying their timezone.

Objective-C - NSTimeZone 2 hours wrong?

I'm using the following code to set my timezone to Stockholm, Europe.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"Europe/Stockholm"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *webUpdateDate = [dateFormatter dateFromString:#"2011-07-22 22:10"];
// Outputs "2011-07-22 20:10 +0000"
Anyone know why?
I assume you're inspecting the date using NSLog. An NSDate object represents an absolute time -- it has no notion of time zone, so when it is asked for its description, it displays as if it were a time in GMT. If you want that absolute time represented for the Stockholm time zone, you need to use the date formatter again:
NSLog(#"%#", [dateFormatter stringFromDate:webUpdateDate]);
Since the date was originally created via the formatter, which already had its time zone set to Stockholm, I believe this will give you the same string that you used for input: #"2011-07-22 22:10".

Convert epoch time to NSDate with good timezone with Objective c

how I can convert an epoch time value to NSDate. For example I use this value : 1310412600000. and I am in the EDT time zone.
When I try this :
NSString *bar = [[NSDate dateWithTimeIntervalSince1970:epoch] description];
I got a wrong value...
What is the good way? I spend a lot of time with that....
Thanks
Epoch time (also known as "Unix" and "POSIX" time) is the number of seconds since the start of 1970. You can convert epoch time to NSDate with this algorithm:
Instantiate NSDate object and pass the epoch time as a parameter to NSDate's initWithTimeIntervalSince1970 initializer. You're done. The NSDate object is set to the epoch time. NSDate stores times internally in the UTC time zone. It's up to you how it is displayed.
[Optional] Format your NSDate to the appropriate time zone with an NSDateFormatter.
Here's the code I used:
// Sample string epochTime is number of seconds since 1970
NSString *epochTime = #"1316461149";
// Convert NSString to NSTimeInterval
NSTimeInterval seconds = [epochTime doubleValue];
// (Step 1) Create NSDate object
NSDate *epochNSDate = [[NSDate alloc] initWithTimeIntervalSince1970:seconds];
NSLog (#"Epoch time %# equates to UTC %#", epochTime, epochNSDate);
// (Step 2) Use NSDateFormatter to display epochNSDate in local time zone
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss zzz"];
NSLog (#"Epoch time %# equates to %#", epochTime, [dateFormatter stringFromDate:epochNSDate]);
// (Just for interest) Display your current time zone
NSString *currentTimeZone = [[dateFormatter timeZone] abbreviation];
NSLog (#"(Your local time zone is: %#)", currentTimeZone);
Per the documentation, dateWithTimeIntervalSince1970: runs from January 1, 1970, 00:00 GMT. So you should be getting results four hours later than those you really want.
Hence the simplest thing — if you don't mind hard coding the offset from GMT to EDT — would seem to be:
[[NSDate dateWithTimeIntervalSince1970:epoch] dateByAddingTimeInterval:-240]
// or:
[NSDate dateWithTimeIntervalSince1970:epoch - 240]
Though to eliminate arbitrary constants (and be a little cleaner), you probably want something like:
NSTimeZone *EDTTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"EDT"];
NSInteger secondsDifferenceFromGMT =
[EDTTimeZone secondsFromGMTForDate:[NSDate dateWithTimeIntervalSince1970:0]];
NSDate *startOfEpoch =
[NSDate dateWithTimeIntervalSince1970:secondsDifferenceFromGMT];
...
NSDate *newDate = [startOfEpoch dateByAddingTimeInterval:firstInterval]; // etc
Are you passing the value in seconds?
The method accepts value in seconds , not milliseconds.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html