1. 程式人生 > >ios開發 獲取系統時間

ios開發 獲取系統時間

取得當前的年月日,當前的時分秒獲得,周幾和星期幾獲得

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];