Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringFromDate always NIL

I know this is a repetitive question, but after searching for many similar questions on stackoverflow and google, none of the solutions worked for me.

I am tring to convert date which I receive from DB to string format to display in iPhone app.

I am converting date to string in following manner, but [dateFormat stringFromDate:beginDate] always return nil.

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMM dd hh:mm a"];
NSString *dateString = [dateFormat stringFromDate:beginDate];
NSLog(@"date: %@", dateString);
[dateFormat release];

The server NSDate received is of following format:

2012-05-23 13:06:51.394+1000

and I want it to

May 25 13:06 PM
like image 449
iOSDev Avatar asked Mar 18 '26 07:03

iOSDev


2 Answers

You need to convert your beginDate string to an actual NSDate first, and then do it:

NSString *beginDateString  = [arr_data objectAtIndex:1];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSZ"];
NSDate *beginDate = [formatter dateFromString:beginDateString];

[formatter setDateFormat:@"MMM dd hh:mm a"];
NSString *dateString = [formatter stringFromDate:beginDate];
NSLog(@"date: %@", dateString);

Note that you say in your question that you want it to output May 25 13:06 PM but it will actually output May 25 01:06 PM. (13:06 would be using 24 hour time instead of 12 hour time and wouldn't need the am/pm.)

like image 126
lnafziger Avatar answered Mar 19 '26 19:03

lnafziger


What is the type of beginDate? If it is NSString, then convert it to NSDate first, by using dateFromString method of NSDateFormatter.

NSString *beginDate = @"2012-05-23 13:06:51.394+1000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

// Set the format of the dateFormatter to the date format of the server
dateFormatter.dateFormat = @"yyyy-MM-dd HH:MM:ss.SSSZ";
// Convert the NSString to NSDate
NSDate* date = [dateFormatter dateFromString: beginDate];

// Set the format of dateFormatter to your own format
dateFormatter.dateFormat = @"MMM dd hh:mm a";
// Convert NSDate to your own format of date
beginDate = [dateFormatter stringFromDate: date];
like image 36
nhahtdh Avatar answered Mar 19 '26 21:03

nhahtdh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!