一. NSString与NSDate之间转化
- NSString转化为NSDate
[dateformatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *date = [NSDate date];
NSString *dateStr = [dateformatter stringFromDate:date];
- NSDate转化为NSString
[dateformatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString = @"2015-07-11 10:00";
NSDate *date = [dateformatter dateFromString:date];
二. 获取当前日期及以后几天日期并加入数组
NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *now = [NSDate date];
NSMutableArray *dayArray = [NSMutableArray array];
for (int i = 0; i <= 365; i ++) {
NSDate *date = [now dateByAddingTimeInterval:i*3600*24];
NSString *dateStr = [formatter stringFromDate:date];
[dayArray addObject:dateStr];
}
注意:转换格式只能用@”yyyy-MM-dd HH:mm:ss”,如果把yyyy写成YYYY,那么就会出现本年度12月份最后几天变成明年的现象,如下图,YYYY是取那一周所在的年份的日期。
三. 获取星期几
//注意:week为1时,是星期日
-(void)week
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit |
NSWeekdayCalendarUnit |
NSHourCalendarUnit |
NSMinuteCalendarUnit |
NSSecondCalendarUnit;
comps = [calendar components:unitFlags fromDate:[NSDate date]];
NSInteger week = [comps weekday];
NSString *weekStr = [self getweek:week];
NSLog(@"%@",weekStr);
}
-(NSString*)getweek:(NSInteger)week
{
NSString*weekStr=nil;
if(week==1)
{
weekStr=@"星期日";
}else if(week==2){
weekStr=@"星期一";
}else if(week==3){
weekStr=@"星期二";
}else if(week==4){
weekStr=@"星期三";
}else if(week==5){
weekStr=@"星期四";
}else if(week==6){
weekStr=@"星期五";
}else if(week==7){
weekStr=@"星期六";
}
return weekStr;
}