您的位置:首页 > 其它

iPhone开发 获取系统时间 星期 年 月 日 时 分 秒

2015-03-26 12:03 351 查看
//获取系统当前时间

- (NSString*)get_system_today_time

{

NSDate *date = [NSDate date];

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

[formatter setDateStyle:kCFDateFormatterMediumStyle];

[formatter setTimeStyle:kCFDateFormatterShortStyle];

[formatter setDateFormat:@"YYYY-MM-dd-hh-mm-ss"];

NSString *string_time = [formatterstringFromDate:date];

NSArray *time = [string_timecomponentsSeparatedByString:@"-"];

int value_year = [[timeobjectAtIndex:0]intValue];

int value_month = [[timeobjectAtIndex:1]intValue];

int value_day = [[timeobjectAtIndex:2]intValue];

int value_hour = [[timeobjectAtIndex:3]intValue];

int value_minute = [[timeobjectAtIndex:4]intValue];

int value_second = [[timeobjectAtIndex:5]intValue];

[formatter setDateFormat:@"EEEE"];

NSString *week_day = [formatter stringFromDate:date];

[formatter release];

NSString *system_time = [[NSStringalloc]initWithFormat:@"{\"year\":\"%d\",\"month\":\"%d\",\"day\":\"%d\",\"hour\":\"%d\",\"minute\":\"%d\",\"second\":\"%d\",\"week_day\":\"%@\"}",value_year,value_month,value_day,value_hour,value_minute,value_second,week_day];

NSLog(@"\nsystem time is %@",system_time);

return [system_timeautorelease];

}

----------------------------------------------------------------------------

NSDate *date
= [NSDate date];

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *comps;

// 年月日获得

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

fromDate:date];

NSInteger year = [comps year];

NSInteger month = [comps month];

NSInteger day = [comps day];

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

//当前的时分秒获得

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

fromDate:date];

NSInteger hour = [comps hour];

NSInteger minute = [comps minute];

NSInteger second = [comps second];

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

// 周几和星期几获得

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

fromDate:date];

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

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

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

NSLog(@"week: %d weekday: %d weekday ordinal: %d", week, weekday, weekdayOrdinal);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: