有时候需要获取当前时间的详细日期:
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//获取当前时间日期展示字符串 如:2019-05-23-13:58:59
NSString *str = [formatter stringFromDate:date];
//下面是单独获取每项的值
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit |NSMonthCalendarUnit |NSDayCalendarUnit |NSWeekdayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit |NSSecondCalendarUnit;
comps = [calendar components:unitFlags fromDate:date];
//星期 注意星期是从周日开始计算
int week = [comps weekday];
//年
int year=[comps year];
//月
int month = [comps month];
//日
int day = [comps day];
//时
int hour = [comps hour];
//分
int minute = [comps minute];
//秒
int second = [comps second];
网友评论