呀嘞呀嘞 好久不写 之前准备毕业 之后又忙着APP改版 所以就...
first step: 获取当前的时间 格式为:NSDate
NSDate *date = [NSDate date];
不要告诉我你不会这句..
second step:转换成字符串:这时候就需要设置需要转换的格式了
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"YYYY MM dd"; // 这个时间展示格式你随意
NSString *str = [formatter stringFromDate:date]; // date转字符串
NSDate *date = [formatter dateFromString:str]; // 字符串转date
啊 对了这是时分秒:hh:mm:ss 不用谢~
这时候要是想要计算年龄 ,如下:
- (NSInteger)agesWithBirthday:(NSDate *)birthdayDate {
if (birthdayDate) {
NSDate *currentDate = [NSDate date];
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekOfYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal) fromDate:currentDate];
NSDateComponents *birthComponents = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekOfYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal) fromDate:birthdayDate];
NSInteger ages = components.year - birthComponents.year;
if (components.month < birthComponents.month) {
ages --;
}
if (components.month == birthComponents.month) {
if (components.day < birthComponents.day) {
ages --;
}
}
NSLog(@"年龄是:%ld", ages);
return ages;
}
return -1;
}
调用:
NSArray *array = @[@"19980101", @"19980111", @"19980903", @"19981003", @"19700901", @"19701001", @"19700903", @"19700801"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"YYYYMMdd";
for (int i = 0; i < array.count; i++) {
NSString *SFZstr = array[i];
NSDate *date = [formatter dateFromString:SFZstr];
[self agesWithBirthday:date];
}
好啦 就是这样 有问题 请指正 谢谢~