基于常用的时间来说,我们平常需要获取的方式很多,而为了简单便捷获取时间方式,封装了以下一些方法,可直接写成NSDate的分类,然后直接通过方法调用获取相关的时间方式。
- 获取当前时间的 年 月 日 如:2018-01-01.
/**
* 获取年月日如:20180101.
*
* @return 年月日如:20180101.
*/
- (NSString *)getFormatYearMonthDay
{
NSString *string = [NSString stringWithFormat:@"%zd%zd%zd",[self getYear],[self getMonth],[self getDay]];
return string;
}
2.获取当前时间的日期是当年的第几周
/**
* 该前时间的日期是该年的第几周
*
* @return 第几周
*/
- (int )getWeekOfYear
{
int i;
int year = (int)[self getYear];
NSDate *date = [self endOfWeek];
for (i = 1;[[date dateAfterDay:-7 * i] getYear] == year;i++)
{
}
return i;
}
3.获取当前时间的日
/**
* 获取当前时间的日
*
* @return 返回当前时间的日
*/
- (NSUInteger)getDay
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponents = [calendar components:(NSCalendarUnitDay) fromDate:self];
return [dayComponents day];
}
4.获取当前时间的月
/**
* 获取当前时间的月
*
* @return 返回当前时间的月
*/
- (NSUInteger)getMonth
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponents = [calendar components:(NSCalendarUnitMonth) fromDate:self];
return [dayComponents month];
}
5.获取当前时间的年
/**
* 获取前时间的年
*
* @return 返回前时间的年
*/
- (NSUInteger)getYear
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponents = [calendar components:(NSCalendarUnitYear) fromDate:self];
return [dayComponents year];
}
6.获取当前时间的小时
/**
* 获取前时间的小时
*
* @return 返回前时间的小时
*/
- (int )getHour
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour |NSCalendarUnitMinute;
NSDateComponents *components = [calendar components:unitFlags fromDate:self];
NSInteger hour = [components hour];
return (int)hour;
}
7.获取当前时间的分钟
/**
* 获取前时间的分钟
*
* @return 返回前时间的小时
*/
- (int)getMinute
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour |NSCalendarUnitMinute;
NSDateComponents *components = [calendar components:unitFlags fromDate:self];
NSInteger minute = [components minute];
return (int)minute;
}
8.获取一周的第几天(周末为第一天)
/**
* 获取一周的第几天(周末为第一天)
*
* @return 返回一周的第几天(周末为第一天
*/
- (NSUInteger)weekday
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [calendar components:(NSCalendarUnitWeekday) fromDate:self];
return [weekdayComponents weekday];
}
9.格式化时间+格式化的类型(格式化String)
/**
* 格式化时间+格式化的类型(格式化String)
*
* @param string 需要格式化的String
* @param format 格式化格式 :如@“yyyy-MM-dd hh-mm-ss”
*
* @return 返回格式化后的时间的date
*/
+ (NSDate *)dateFromString:(NSString *)string withFormat:(NSString *)format
{
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:format];
NSDate *date = [inputFormatter dateFromString:string];
return date;
}
- 格式化时间+格式化的类型(格式化NSData)
/**
格式化类型
@param format 格式化类型
@return 返回格式化后的字符串
*/
- (NSString *)stringWithFormat:(NSString *)format {
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:format];
NSString *timestamp_str = [outputFormatter stringFromDate:self];
return timestamp_str;
}
/**
* 格式化时间+格式化的类型
*
* @param date 需要格式化的Date
* @param format 格式化格式 :如@“yyyy-MM-dd hh-mm-ss”
*
* @return 返回格式化后的时间字符串
*/
+ (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString *)format
{
return [date stringWithFormat:format];
}
11.字符串时间格式化字符串时间 (String -> String)
/**
* 字符串时间格式化字符串时间 (String -> String)
*
* @param dateString 需要格式化的时间String
* @param dateStringFormatter 需要格式化的时间String的格式(必须与传进来的String的格式一致)yyyy-MM-dd HH:mm:ss hh 为12小时制 HH 为24小时制
* @param formatter 格式化后的格式
*
* @return 格式化后的时间
*/
+ (NSString *)stringFromString:(NSString *)dateString andDateStringFormatter:(NSString *)dateStringFormatter withFormatter:(NSString *)formatter
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:dateStringFormatter];
NSDate *date1 = [dateFormatter dateFromString:dateString];
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
[dateFormatter2 setDateFormat:formatter];
NSString *strDate1 = [dateFormatter2 stringFromDate:date1];
return strDate1;
}
12.添加时间作为前缀
/**
* 添加时间作为前缀
*
* @param date 时间date
* @param prefixed 是否前缀
*
* @return 返回是否加了前缀的时间
*/
+ (NSString *)stringForDisplayFromDate:(NSDate *)date prefixed:(BOOL)prefixed
{
NSDate *today = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *offsetComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
fromDate:today];
NSDate *midnight = [calendar dateFromComponents:offsetComponents];
NSDateFormatter *displayFormatter = [[NSDateFormatter alloc] init];
NSString *displayString = nil;
// comparing against midnight
if ([date compare:midnight] == NSOrderedDescending) {
if (prefixed) {
[displayFormatter setDateFormat:@"'at' h:mm a"]; // at 11:30 am
} else {
[displayFormatter setDateFormat:@"h:mm a"]; // 11:30 am
}
} else {
// check if date is within last 7 days
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay:-7];
NSDate *lastweek = [calendar dateByAddingComponents:componentsToSubtract toDate:today options:0];
if ([date compare:lastweek] == NSOrderedDescending) {
[displayFormatter setDateFormat:@"EEEE"]; // Tuesday
} else {
// check if same calendar year
NSInteger thisYear = [offsetComponents year];
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
fromDate:date];
NSInteger thatYear = [dateComponents year];
if (thatYear >= thisYear) {
[displayFormatter setDateFormat:@"MMM d"];
} else {
[displayFormatter setDateFormat:@"MMM d, yyyy"];
}
}
if (prefixed) {
NSString *dateFormat = [displayFormatter dateFormat];
NSString *prefix = @"'on' ";
[displayFormatter setDateFormat:[prefix stringByAppendingString:dateFormat]];
}
}
// use display formatter to return formatted date string
displayString = [displayFormatter stringFromDate:date];
return displayString;
}
13.获取以周一为第一天开始的时间
/**
* 获取以周一为第一天开始的时间
*
* @return 返回周一的的开始时间
*/
- (NSDate *)beginningOfWeek
{
// largely borrowed from "Date and Time Programming Guide for Cocoa"
// we'll use the default calendar and hope for the best
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *beginningOfWeek = nil;
calendar.firstWeekday = 2;
// couldn't calc via range, so try to grab Sunday, assuming gregorian style
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [calendar components:NSCalendarUnitWeekday fromDate:self];
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 2)];
beginningOfWeek = nil;
beginningOfWeek = [calendar dateByAddingComponents:componentsToSubtract toDate:self options:0];
//normalize to midnight, extract the year, month, and day components and create a new date from those components.
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay)
fromDate:beginningOfWeek];
return [calendar dateFromComponents:components];
}
14.获取某天后的日期(若day为负数,则为|day|天前的日期)
/**
* 获取某天后的日期(若day为负数,则为|day|天前的日期)
*
* @param day 某天
*
* @return 返回day天后的日期(若day为负数,则为|day|天前的日期)
*/
- (NSDate *)dateAfterDay:(int)day
{
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
// NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:self];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
// to get the end of week for a particular date, add (7 - weekday) days
[componentsToAdd setDay:day];
NSDate *dateAfterDay = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
return dateAfterDay;
}
15.获取某个月后的日期
/**
* 获取某个月后的日期
*
* @param month 某个月
*
* @return 某个月个月后的日期
*/
- (NSDate *)dateafterMonth:(int)month
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
[componentsToAdd setMonth:month];
NSDate *dateAfterMonth = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
return dateAfterMonth;
}
16.获取当前月的第一天
/**
* 获取当前月的第一天
*
* @return 返回该月的第一天
*/
- (NSDate *)beginningOfMonth
{
return [self dateAfterDay:(int)(-[self getDay] + 1)];
}
17.获取该月的最后一天
/**
* 获取该月的最后一天
*
* @return 该月的最后一天
*/
- (NSDate *)endOfMonth
{
return [[[self beginningOfMonth] dateafterMonth:1] dateAfterDay:-1];
}
18.获取当前周的周末的时间
/**
* 获取当前周的周末
*
* @return 当前周的周末
*/
- (NSDate *)endOfWeek
{
NSCalendar *calendar = [NSCalendar currentCalendar];
// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [calendar components:NSCalendarUnitWeekday fromDate:self];
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
// to get the end of week for a particular date, add (7 - weekday) days
[componentsToAdd setDay:(7 - [weekdayComponents weekday])];
NSDate *endOfWeek = [calendar dateByAddingComponents:componentsToAdd toDate:self options:0];
return endOfWeek;
}
19.获取当前时间的上一个月的时间
/**
* 获取上一个月的时间
*/
+ (NSString *)getLastMonth
{
NSDate *currentDate = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
// [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期,month day 类推
[lastMonthComps setMonth:-1];
NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
NSString *dateStr = [formatter stringFromDate:newdate];
// NSLog(@"date str = %@", dateStr);
return dateStr;
}
20.获取距离当前月的某个月份时间
/**
* 获取距离当前月的某个月份
*
* @param distanceMonth 距离当前月的月份 负数是前多少个月 ,正数为后几个月
*
* @return 距离当前月的某个月份
*/
+ (NSString *)getDistanceCurrentMonthWhichMonth:(int)distanceMonth
{
NSDate *currentDate = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
// [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期,month day 类推
[lastMonthComps setMonth:distanceMonth];
NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
NSString *dateStr = [formatter stringFromDate:newdate];
// NSLog(@"date str = %@", dateStr);
return dateStr;
}
21.获取距离当前时间后的某个小时
/**
* 获取距离当前时间后的某个小时
*
* @param distanceHours 距离当前时间的小时数 负数是前多少个小时 ,正数为后几个小时
*
* @return 距离当前月的某个月份
*/
+ (NSString *)getDistanceCurrentHourWhichHour:(int)distanceHours
{
NSDate *currentDate = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *lastHourComps = [[NSDateComponents alloc] init];
// [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期,month day 类推
[lastHourComps setHour:distanceHours];
NSDate *newdate = [calendar dateByAddingComponents:lastHourComps toDate:currentDate options:0];
NSString *dateStr = [formatter stringFromDate:newdate];
// NSLog(@"date str = %@", dateStr);
return dateStr;
}
22.获取距离某个时间后的某个小时
/**
* 获取距离某个时间后的某个小时
*
* @param date 当前时间
* @param distanceHours 距离当前时间的小时数 负数是前多少个小时 ,正数为后几个小时
* @param formatterString 时间类型
*
* @return 距离当前月的某个月份
*/
+ (NSString *)getDistanceCurrentHourWithDate:(NSDate *)date andWhichHours:(int)distanceHours withFormatterString:(NSString *)formatterString
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:formatterString];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *lastHourComps = [[NSDateComponents alloc] init];
// [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期,month day 类推
[lastHourComps setHour:distanceHours];
NSDate *newdate = [calendar dateByAddingComponents:lastHourComps toDate:date options:0];
NSString *dateStr = [formatter stringFromDate:newdate];
// NSLog(@"date str = %@", dateStr);
return dateStr;
}
23.获取指定月的第一天的时间
/**
* 获取指定月的第一天的时间
*
* @param dateStr 指定月的字符串
*
* @return 指定月的第一天
*/
+ (NSString *)getMonthBeginWith:(NSString *)dateStr
{
NSDateFormatter *format=[[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM"];
NSDate *newDate=[format dateFromString:dateStr];
double interval = 0;
NSDate *beginDate = nil;
NSDate *endDate = nil;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setFirstWeekday:2];//设定周一为周首日
BOOL ok = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&beginDate interval:&interval forDate:newDate];
//分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
if (ok) {
endDate = [beginDate dateByAddingTimeInterval:interval-1];
}else {
return @"";
}
NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:@"dd"];
NSString *beginString = [myDateFormatter stringFromDate:beginDate];
return [NSString stringWithFormat:@"%@-%@",dateStr,beginString];;
}
24.获取指定月的最后一天的时间
/**
* 获取指定月的最后一天的时间
*
* @param dateStr 指定月的字符串
*
* @return 指定月的最后一天
*/
+ (NSString *)getMonthEndWith:(NSString *)dateStr
{
NSDateFormatter *format=[[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM"];
NSDate *newDate=[format dateFromString:dateStr];
double interval = 0;
NSDate *beginDate = nil;
NSDate *endDate = nil;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setFirstWeekday:2];//设定周一为周首日
BOOL ok = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&beginDate interval:&interval forDate:newDate];
// 分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
if (ok) {
endDate = [beginDate dateByAddingTimeInterval:interval-1];
}else {
return @"";
}
NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:@"dd"];
NSString *endString = [myDateFormatter stringFromDate:endDate];
return [NSString stringWithFormat:@"%@-%@",dateStr,endString];
}
25.获取两个日期之间的天数差
/**
* 获取两个日期之间的天数差
*
* @param fromDate 起始日期
* @param toDate 终止日期
*
* @return 总天数
*/
+ (NSInteger)numberOfDaysWithFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents * comp = [calendar components:NSCalendarUnitDay
fromDate:fromDate
toDate:toDate
options:NSCalendarWrapComponents];
return comp.day;
}
26.获取两个日期之间的小时差
/**
* 获取两个日期之间的小时差
*
* @param fromDate 起始日期
* @param toDate 终止日期
*
* @return 总相差小时
*/
+ (NSInteger)numberOfHourWithFromDate:(NSString *)fromDateString toDate:(NSString *)toDateString WithFormatterString:(NSString *)formatterString
{
// 2.将时间转换为date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = formatterString;
NSDate *date1 = [formatter dateFromString:fromDateString];
NSDate *date2 = [formatter dateFromString:toDateString];
// 3.创建日历
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
// 4.利用日历对象比较两个时间的差值
NSDateComponents *cmps = [calendar components:type fromDate:date1 toDate:date2 options:0];
// 5.输出结果
NSLog(@"两个时间相差%ld年%ld月%ld日%ld小时%ld分钟%ld秒", (long)cmps.year, (long)cmps.month, (long)cmps.day, (long)cmps.hour, (long)cmps.minute, (long)cmps.second);
NSInteger hours = cmps.hour + cmps.day * 24 + cmps.month * 30 * 24 +cmps.year * 365 *30 *24;
return hours;
}
27.获取两个日期之间的分钟差
/**
* 获取两个日期之间的分钟差
*
* @param fromDate 起始日期
* @param toDate 终止日期
*
* @return 总相差分
*/
+ (NSInteger)numberOfMinWithFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents * comp = [calendar components:NSCalendarUnitDay
fromDate:fromDate
toDate:toDate
options:NSCalendarWrapComponents];
return comp.minute;
}
28.判断某个时间段是否为今天
/**
* 判断某个时间段是否为今天
*
* @param dateString 某个时间段
*
* @return 是否是今天 YES:今天 NO:不是今天
*/
+ (BOOL)isTodayWithDateString:(NSString *)dateString
{
//now: 2015-09-05
//self 调用这个方法的对象本身
NSString *str = dateString;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:str];
NSCalendar *calendar = [NSCalendar currentCalendar];
int unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear ;
//1.获得当前时间的 年月日
NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
//2.获得self
NSDateComponents *selfCmps = [calendar components:unit fromDate:date];
return (selfCmps.year == nowCmps.year) && (selfCmps.month == nowCmps.month) && (selfCmps.day == nowCmps.day);
}
29.比较两个时间段的大小
/**
* 比较两个时间段的大小
*
* @param dateStr01 时间段1
* @param dateStr02 时间段2
* @param formatter 格式
*
* @return 1: 时间段1 < 时间段2 0: 时间段1 = 时间段2 -1: 时间段1 > 时间段2
*/
+ (int)compareStringDate:(NSString*)dateStr01 withStringDate:(NSString*)dateStr02 withFormatter:(NSString *)formatter
{
int different;
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:formatter];
NSDate *dt1 = [[NSDate alloc]init];
NSDate *dt2 = [[NSDate alloc]init];
dt1 = [df dateFromString:dateStr01];
dt2 = [df dateFromString:dateStr02];
NSComparisonResult result = [dt1 compare:dt2];
switch (result)
{
//date02比date01大
case NSOrderedAscending: different = 1;
break;
//date02比date01小
case NSOrderedDescending: different = -1;
break;
//date02=date01
case NSOrderedSame: different=0;
break;
default: NSLog(@"erorr dates %@, %@", dt2, dt1);
break;
}
return different;
}
以上是对于NSDate的分类一些方法进行相关封装,在NSDate中对时间的处理,更加看重的是对时间的格式化之余需要注意时间相关的格式,只有统一的格式才能进行计算和进行比较,否则会导致程序报错,直接崩溃。如有什么不明之处欢迎交流,也欢迎大家指出相关的错误点。
大千世界,求同存异;相遇是缘,相识是份,相知便是“猿粪”(缘分)
From MZou