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

  

 

 

//后台时间戳转化为yyyyMMdd

  const long long dateTimeLong =[value longLongValue]/1000;

                

                NSDate *dateTime = [[NSDate alloc] initWithTimeIntervalSince1970:dateTimeLong];

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

                [formatter setTimeStyle:NSDateFormatterNoStyle];

                [formatter setDateStyle:NSDateFormatterMediumStyle];

                NSLocale *formatterLocal = [[NSLocale alloc] initWithLocaleIdentifier:@"en_us"];

                [formatter setLocale:formatterLocal];

                [formatter setDateFormat:@"yyyyMMdd"];

                NSDate *new = [NSDate dateWithTimeInterval:0 sinceDate:dateTime];

                NSString *dateString = [formatter stringFromDate:new];

 

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。