最近项目中常常用到关于时间的判断和使用,总结了一下常用到的关于NSDate的基础知识
获取当天日期
NSDate* date = [NSDate date];
获取明天日期
`+ (NSDate)nextDateWithDate:(NSDate)date
{
NSString* dateStr = @"";
NSInteger day = [self dayWithDate:date];
NSInteger days = [self getNumberOfDaysInMonthWithdate:date];
if (day + 1 > days) {
NSInteger month = [self monthWithDate:date];
if (month + 1 > 12) {
NSInteger year = [self yearWithDate:date];
dateStr = [NSString stringWithFormat:@"%ld-%d-%d", year + 1, 1, 1];
}
else {
dateStr = [NSString stringWithFormat:@"%ld-%ld-%d", (long)[self yearWithDate:date], month + 1, 1];
}
}
else {
dateStr = [NSString stringWithFormat:@"%ld-%ld-%ld", (long)[self yearWithDate:date], (long)[self monthWithDate:date], (day + 1)];
}
return [self strToDateWithStr:dateStr];
}`
获取几天是几号
+ (NSInteger)dayWithDate:(NSDate*)date { NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日历的算法 NSCalendarIdentifierGregorian,NSGregorianCalendar // NSDateComponent 可以获得日期的详细信息,即日期的组成 NSDateComponents* comps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date]; return comps.day; }
获取几天是几月
+ (NSInteger)monthWithDate:(NSDate*)date { NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日历的算法 NSCalendarIdentifierGregorian,NSGregorianCalendar // NSDateComponent 可以获得日期的详细信息,即日期的组成 NSDateComponents* comps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date]; return comps.month; }
获取今天是哪一年
+ (NSInteger)yearWithDate:(NSDate*)date { NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日历的算法 NSCalendarIdentifierGregorian,NSGregorianCalendar // NSDateComponent 可以获得日期的详细信息,即日期的组成 NSDateComponents* comps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date]; return comps.year; }
一个月共有几天
+ (NSInteger)getNumberOfDaysInMonthWithdate:(NSDate*)date { NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日历的算法 // 只要个时间给日历,就会帮你计算出来。这里的时间取当前的时间。 NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date]; return range.length; }
日期和字符串之间的转换
+ (NSDate*)strToDateWithStr:(NSString*)dateStr { NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd"]; // 年-月-日 时:分:秒 // 这个格式可以随便定义,比如:@"yyyy,MM,dd,HH,mm,ss" NSDate* date = [formatter dateFromString:dateStr]; NSLog(@"the date = %@", date); return date; }
+ (NSString*)dateToStrWithDate:(NSDate*)date { NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd"]; //只获取月和日的数据 NSString* dateString = [formatter stringFromDate:date]; NSLog(@"dateString = %@", dateString); // 这样就可以获得月和日的字符串,通过字符串截取的手段也可以获得月和日的数据 return dateString; }
网友评论