Converting an integer to a date string

In Objective-C: is there an easy way, like in Excel and SAS, to convert an integer to a datetime string?

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

For example, if I had an integer: 1328062560

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

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

PS: I do not want to be too demanding, but I would like simple and built-in for use in NSLog, so I can write just for debugging
NSLog ("Time as integer% d and as date% mmmddyyyyhh: mm: ss", [array objectAtIndex: i], [array objectAtIndex: i]);

+5
source share
3 answers

You can get the object NSDateas follows:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:1328062560];

Then, if you do not need the exact format of the string, you can simply do this:

NSString *s = [date description];

This will give you a string like " 2012-02-01 02:16:00 +0000".

If you need a specific string format, use NSDateFormatter.

+12
source

You can use NSDateFormatterfor this. First you create a string from your integer value:

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

And then create NSDateFormatterwith the appropriate format:

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

Then you can get the date as a string in the desired format:

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

, , NSDate initWithTimeIntervalSince1970 dateWithTimeIntervalSince1970 NSDate , NSDateFormatter .

+1

All Articles