问题与date格式使用NSDateFormatter

我有一个datestring,我想要转换为另一种格式。

原始datestring的例子是: “2013-06-04 02:19:21 +0000”

我想将其转换为“星期三,六月四日”

NSString * date_string = @"2013-06-04 02:19:21 +0000"; NSDateFormatter *complexdateFormater = [[NSDateFormatter alloc] init]; [complexdateFormater setDateFormat:@"yyyy-M-DD HH:mm:ss Z"]; NSDate* complexdate = [complexdateFormater dateFromString:date_string]; NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"EE, MMM d" options:0 locale:[NSLocale currentLocale]]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:formatString]; NSString *todayString = [dateFormatter stringFromDate:complexdate]; 

但是对于上述情况的今天的string打印出来:月份作为Jan,而不考虑原始string中的月份值。

我哪里错了?

在这里,你去我的朋友

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"EEE, MMM dd"]; NSString *theDate = [dateFormat stringFromDate:date1]; 

date格式化程序参考其他人可能访问此post。 如果它有帮助,请评价它!

 /* x number xx two digit number xxx abbreviated name xxxx full name a AM/PM A millisecond of day c day of week (c,cc,ccc,cccc) d day of month e day of week (e,EEE,EEEE) F week of month g julian day (since 1/1/4713 BC) G era designator (G=GGG,GGGG) h hour (1-12, zero padded) H hour (0-23, zero padded) L month of year (L,LL,LLL,LLLL) m minute of hour (0-59, zero padded) M month of year (M,MM,MMM,MMMM) Q quarter of year (Q,QQ,QQQ,QQQQ) s seconds of minute (0-59, zero padded) S fraction of second u zero padded year v general timezone (v=vvv,vvvv) w week of year (0-53, zero padded) y year (y,yy,yyyy) z specific timezone (z=zzz,zzzz) Z timezone offset +0000 sql yMd H:m:s rss [E, ]d MMM y[y] H:m:s Z|z[zzz] */ 

用这个replace你的代码

 NSString * date_string = @"2013-06-04 02:19:21 +0000"; NSDateFormatter *complexdateFormater = [[NSDateFormatter alloc] init]; [complexdateFormater setDateFormat:@"EEE, MMM dd"]; NSDate* complexdate = [complexdateFormater dateFromString:date_string]; 

如果你想检查date做这个,而不是NSLog,因为NSLog只以格式返回date…

 NSLog(@"Converted date: %@", [complexdateFormater stringFromDate:complexDate]); 

那么开始吧,你在+0000之后有两个引号。 林不知道这是否是这个职位的错字,但它可能会影响一些东西。

这条线:

 [complexdateFormater setDateFormat:@"yyyy-M-DD HH:mm:ss Z"]; 

应该是这样的:

 [complexdateFormater setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"]; 

在你的datestring的月份是06不只是6,所以你需要两个月的数字:)此外,你需要DD为DD,如rmaddy指出。