Peter_from_NYC
Peter_from_NYC

Reputation: 309

Convert integer to a date string

In Objective-C: Is there a simple way, as in Excel and SAS, to convert an integer into a datetime string?

In Excel, you'd format to "mmm dd, yyyy hh:mm:ss".

For instance, if I had the integer: 1328062560

and I want the output to be: 2012-01-31 21:16:00

or even (as in Excel): Jan 31, 2012 21:16:00

PS: I don't want to be too demanding, but I'd like it simple and inline for use in NSLog, so I can write simply for debugging
NSLog("The time as an integer is %d and as a date %mmmddyyyyhh:mm:ss", [array objectAtIndex: i], [array objectAtIndex: i]);

Upvotes: 5

Views: 4120

Answers (3)

rob mayoff
rob mayoff

Reputation: 385540

You can get an NSDate object like this:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:1328062560];

Then, if you don't care about the exact format of the string, you can just do this:

NSString *s = [date description];

That will give you a string like “2012-02-01 02:16:00 +0000”.

If you want a specific string format, use an NSDateFormatter.

Upvotes: 12

Carl Norum
Carl Norum

Reputation: 224864

Assuming that integer is a time in seconds since the epoch, you can use NSDate's initWithTimeIntervalSince1970 or dateWithTimeIntervalSince1970 methods to create an NSDate object with the date you care about, and then use NSDateFormatter to pretty it up for display.

Upvotes: 1

Iñigo Beitia
Iñigo Beitia

Reputation: 6353

You can use NSDateFormatter to do this. You first make a string from your integer value:

NSString *dateString = [NSString stringWithFormat:@"%d", integerDate];

And then create an NSDateFormatter with the corresponding format:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:@"yyyyMMddhhmm"]; // Change to suit your format
NSDate *dateFromString = [myDateFormatter dateFromString:dateString];

You can then retrieve the date as a string in the format you want:

[myDateFormatter setDateFormat:@"yyyy/MM/dd hh:mm"]; // Change to suit your format
NSString *stringFromDate = [formatter stringFromDate:dateFromString];

Upvotes: 1

Related Questions