stringFromDate always NIL

对着背影说爱祢 提交于 2019-12-06 04:22:19

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.)

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

EDIT2: (Fixed a typo and add full working example)

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];

There is nothing wrong in above code, it works fine with current date. Just replace

NSString *dateString = [dateFormat stringFromDate:beginDate];

by

NSString *dateString = [dateFormat stringFromDate:[NSDate date]];

and will work.

It seems that there is problem with your beginDate.

caohuan

May be your beginDate's format is like "2013-09-29 14:57:48.0",but the dataFormate is

[dFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]

change to "yyyy-MM-dd HH:mm:ss.0" will be OK

You need to call setDateFormat before calling stringFromDate

 NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm dd/MM/yyyy"];
 NSString * dateString =[dateFormatter stringFromDate:someDate];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!