你能帮我进行这样的转换吗 我有 NSString 日期,例如@“2/8/2012 7:21:09 PM” 我需要在输出中包含这样的字符串: “2 月 8 日晚上 7:21” 我尝试使用具有不同日期模式的 dateFormatter 但它总是返回 null..我真的不明白我哪里做错了:(
NSString *dateString = newsItem.Date;//Which is equal to @"2/8/2012 7:21:09 PM"
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm/dd/yyyy hh:mm:ss"];//I'm sure that this patternt is wrong but have no idea how to write the right one
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
NSLog(@"date:%@", dateFromString);
最佳答案
您需要使用两种不同的日期格式化程序。第一个将字符串转换为日期,第二个将日期输出为具有指定格式的字符串。
NSString* dateString = @"2/8/2012 7:21:09 PM";
NSDateFormatter* firstDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[firstDateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate* date = [firstDateFormatter dateFromString:dateString];
NSLog(@"Date = %@",date);
NSDateFormatter* secondDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[secondDateFormatter setDateFormat:@"h:mm a, MMMM d"];
NSString* secondDateString = [NSString stringWithFormat:@"at %@",[secondDateFormatter stringFromDate:date]];
NSLog(@"%@",secondDateString);
诀窍是日期格式字符串。他们使用一种叫做unicode日期格式的格式,规范可以参见here .
关于iphone - 将 NSString 日期转换为 NSDate 或特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9281365/