Duny
Duny

Reputation: 215

Objective C Timestamp

I have found numerous timestamp conversions and they all work but the thing is, when I put my code to the text form of the date, I always come out 4 months ahead.

This is pulling the current Day of Week, Date and Time. I have it set this way cause I select the day with a DateTime Picker. This is just my viewDidLoad to pull today's date.

NSDate *myDate = [[NSDate alloc] init];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"cccc, MMMM dd, YYYY, hh:mm aa"];
NSString *prettyVersion = [dateFormat stringFromDate:myDate];
date.text = prettyVersion;

Now comes the timestamp conversion to take prettyVersion to timeIntervalSince1970

NSDate *startdates = [dateFormat dateFromString:prettyVersion];
NSLog(@"Timestamp %0.0f",[startdates timeIntervalSince1970]);

NSLog outputs "Timestamp 1356317580" which when converted is Mon, 24 Dec 2012 02:53:00 GMT

Now I can do this

          NSLog(@"Timestamp2  %0.0f",[myDate timeIntervalSince1970]);

and get the right timestamp.

So where am i messing up at.

Upvotes: 9

Views: 9436

Answers (1)

NickH
NickH

Reputation: 683

This question has already been answered here: NSDateFormatter dateFromString gives the wrong date

But the gist of it is in your date dateFormat you should use "yyyy" instead of "YYYY".

From the apple documentation:

A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

[dateFormat setDateFormat:@"cccc, MMMM dd, yyyy, hh:mm aa"];

And then for me it would format to "Sunday, September 15, 2013, 07:24 PM" which is what it was when I ran this to test.

Upvotes: 7

Related Questions