// Do any additional setup after loading the view, typically from a nib.
//得到当前的日期 注意week1是星期天
NSDate *date = [NSDate date];
NSLog(@"date:%@",date); //得到(24 * 60 * 60)即24小时之前的日期,dateWithTimeIntervalSinceNow:
NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow: -(24* 60* 60)];
NSLog(@"yesterday:%@",yesterday); NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
//NSDate *date_ = [NSDate date];
[formatter setTimeStyle:NSDateFormatterMediumStyle];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit |
NSWeekdayCalendarUnit |
NSHourCalendarUnit |
NSMinuteCalendarUnit |
NSSecondCalendarUnit; //int week=0;week1是星期天,week7是星期六;
comps = [calendar components:unitFlags fromDate:date];
int week = [comps weekday];
int year=[comps year];
int month = [comps month];
int day = [comps day]; //[formatter setDateStyle:NSDateFormatterMediumStyle]; //This sets the label with the updated time. int hour = [comps hour];
int min = [comps minute];
int sec = [comps second];
NSLog(@"week:%d : %@",week,[self week:week]);
NSLog(@"year:%d",year);
NSLog(@"month:%d",month);
NSLog(@"day:%d",day);
NSLog(@"hour:%d",hour);
NSLog(@"min:%d",min);
NSLog(@"sec:%d",sec); //得到毫秒
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
//[dateFormatter setDateFormat:@"hh:mm:ss"]
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
NSLog(@"Date:%@", [dateFormatter stringFromDate:[NSDate date]]);

-(NSString*)week:(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;
}

由NSDate
转换为NSString:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", strDate);

由NSString
转换为NSDate:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:@"2010-08-04 16:01:03"];
NSLog(@"%@", date);
04-26 08:16