NSString*dateStr = @"Wed May 222:27:08+0800 2012";
NSDateFormatter* formater =[[NSDateFormatter alloc] init];
[formater setDateFormat:@"EEE MMM d HH:mm:sszzzz yyyy"];上面代码在真机上运行后,发现取得date为NULL,模拟器正常显示,上网搜索后发现需要设置local, 果然设置后,真机正常
NSLocale* local =[[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"] autorelease];
[formatter setLocale: local];
4、自定义显示的 星期 格式
使用NSDateFormatter转换日期时,得到的英文字母的星期几只能是这样,如Sun, Mon, etc.
如果想得到大写字母的星期几,可以这样:
NSArray*weekdayAry = [NSArray arrayWithObjects:@"SUN", @"MON", @"TUE",@"WED", @"THU", @"FRI", @"SAT", nil];
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:NSLocalizedString(@"YYYY.MM.dd.eee",nil)];
//此处更改显示的大写字母的星期几
[dateFormattersetShortWeekdaySymbols:weekdayAry];
[dateFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"] ]];
NString *str= [dateFormatter stringFromDate:[NSDate date]];
5、计算距离某一天还有多少时间
NSDate* toDate = [ [ NSDate alloc]initWithString:@"2012-9-29 0:0:00 +0600" ];
NSDate* startDate = [ [ NSDatealloc] init ];
NSCalendar* chineseClendar = [ [ NSCalendar alloc ]initWithCalendarIdentifier:NSGregorianCalendar ];
NSUInteger unitFlags =
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit |NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;
NSDateComponents *cps = [chineseClendar components:unitFlagsfromDate:startDate toDate:toDate options:0];
NSInteger diffHour = [cps hour];
NSInteger diffMin = [cpsminute];
NSInteger diffSec = [cps second];
NSInteger diffDay = [cps day];
NSInteger diffMon = [cps month];
NSInteger diffYear = [cps year];
NSLog( @" From Now to %@, diff: Years:%d Months: %d, Days; %d, Hours: %d, Mins:%d,sec:%d",
[toDate description], diffYear, diffMon, diffDay, diffHour,diffMin,diffSec );