我正在尝试将日期从MMM dd,YYYY转换为YYYY-MM-dd。
NSDateFormatter *importDateFormat = [[NSDateFormatter alloc] init];
[importDateFormat setDateFormat:@"MMM dd, YYYY"];
NSDate *importedDate = [importDateFormat dateFromString:expiresOn.text];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd"];
NSString *dateImported = [dateFormat stringFromDate:importedDate];从expiresOn.text (标签)带来的日期是: 2012年10月8日
转换后dateImported中包含的日期为: 2011-12-25
我是不是遗漏了什么?我的日期格式化程序有问题吗?
发布于 2011-11-22 20:57:14
有两件事是错误的,首先是yyyy而不是YYYYY,并且由于您将月份解析为一个单词,因此您需要告诉日期格式化程序应该使用哪种语言。
NSDateFormatter *importDateFormat = [[NSDateFormatter alloc] init];
[importDateFormat setDateFormat:@"MMM dd, yyyy"];
importDateFormat.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en"] autorelease];
NSDate *importedDate = [importDateFormat dateFromString:expiresOn.text];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSString *dateImported = [dateFormat stringFromDate:importedDate];如果您使用的是ARC,则删除NSLocale中的自动释放部件;如果您不使用ARC,则需要释放NSDateFormatter。
https://stackoverflow.com/questions/8227082
复制相似问题