IOS获取时间示例, 获取全年第几周, 月第几周, 周几

时间:2022-09-27 23:06:08
取得当前的年月日,当前的时分秒获得,周几和星期几获得

NSDate*date = [NSDate date];


NSCalendar*calendar = [NSCalendar currentCalendar];


NSDateComponents*comps;


// 年月日获得


comps =[calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)


                                      fromDate:date];


NSIntegeryear = [comps year];


NSIntegermonth = [comps month];


NSIntegerday = [comps day];


NSLog(@"year:%d month: %d, day: %d", year, month, day);


 


//当前的时分秒获得


comps =[calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit)


                                      fromDate:date];


NSIntegerhour = [comps hour];


NSIntegerminute = [comps minute];


NSIntegersecond = [comps second];


NSLog(@"hour:%d minute: %d second: %d", hour, minute, second);


 


// 周几和星期几获得


comps =[calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit |NSWeekdayOrdinalCalendarUnit)


                                      fromDate:date];


NSInteger week = [comps week]; // 今年的第几周


NSIntegerweekday = [comps weekday]; // 星期几(注意,周日是“1”,周一是“2”。。。。)


NSIntegerweekdayOrdinal = [comps weekdayOrdinal]; // 这个月的第几周


NSLog(@"week:%d weekday: %d weekday ordinal: %d", week, weekday, weekdayOrdinal);


 


NSDateFormatter*dateFormatter = [[NSDateFormatter alloc]init];


       if(dateSwitch.on)


       [dateFormattersetDateFormat:@"dd-MMM-yyy,hh:mm:ss"];


       else


       [dateFormatter setDateFormat:@"hh:mm:ss"];


       labelTime.text = [dateFormatter stringFromDate:[NSDatedate]];


       labelTime.font = [UIFontsystemFontOfSize:fontSlider.value];


       [dateFormatter release];



转自: http://gaohaijun.blog.163.com/blog/static/1766982712011923417813/