How to get yyyy-mm-dd hh:mm:ss format from 28 Jul

2019-06-08 11:38发布

问题:

I have stuck in issue in which i have to convert date format is Thu, 28 Jul 2011 22:33:57 +0000 into yyyy-mm-dd hh:mm:ss
please give me some idea how to do this?

回答1:

What you want is to use the NSDateFormatter. Something like this:

NSDateFormatter* f = [[[NSDateFormatter alloc] init] autorelease];
[f setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSString* dateString = [f stringFromDate:date];

Do note that the hours will still follow the users selected locale. Use kk:mm:ss to enforce a 24-hour time.



回答2:

what have you tried? it's difficult to answer questions like this...

first you have to parse the date into an NSDate, use an NSDateFormatter, the incoming format looks like POSIX date format so should be easy.

then you want to output to the format you specify with another NSDateFormatter



回答3:

You need to use an NSDateformatter to convert the first date to a string with the following syntax.

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: @"yyyy-MM-dd hh:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate: [NSDate date]]; //Put whatever date you want to convert

Then if you want the date as an NSDate and you have the string generated above just put the following code.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: @"yyyy-MM-dd hh:mm:ss"];
NSDate * date = [dateFormatter dateFromString: dateString]; //String generated above