各种时间获取

#pragma mark ---

#pragma mark --- 各种方法

/**

*  根据当前月获取有多少天

*

*  @param dayDate 但前时间

*

*  @return 天数

*/

- (NSInteger)getNumberOfDays:(NSDate *)dayDate

{

NSCalendar *calendar = [NSCalendar currentCalendar];

NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:dayDate];

return range.length;

}

/**

*  根据前几月获取时间

*

*  @param date  当前时间

*  @param month 第几个月 正数为前  负数为后

*

*  @return 获得时间

*/

- (NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month

{

[self.comps setMonth:month];

NSDate *mDate = [self.calender dateByAddingComponents:self.comps toDate:date options:0];

return mDate;

}

/**

*  根据时间获取周几

*

*  @param inputDate 输入参数是NSDate,

*

*  @return 输出结果是星期几的字符串。

*/

- (NSString*)weekdayStringFromDate:(NSDate*)inputDate {

[self.calender setTimeZone: self.timeZone];

NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;

NSDateComponents *theComponents = [self.calender components:calendarUnit fromDate:inputDate];

return [self.weekdays objectAtIndex:theComponents.weekday];

}

/**

*  获取第N个月的时间

*

*  @param currentDate 当前时间

*  @param index 第几个月 正数为前  负数为后

*

*  @return @“2016年3月”

*/

- (NSArray*)timeString:(NSDate*)currentDate many:(NSInteger)index;

{

NSDate *getDate =[self getPriousorLaterDateFromDate:currentDate withMonth:index];

NSString  *str =  [self.formatter stringFromDate:getDate];

return [str componentsSeparatedByString:@"-"];

}

/**

*  根据时间获取第一天周几

*

*  @param dateStr 时间

*

*  @return 周几

*/

- (NSString*)getMonthBeginAndEndWith:(NSDate *)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:dateStr];

//分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit

if (ok) {

endDate = [beginDate dateByAddingTimeInterval:interval-1];

}else {

return @"";

}

return  [self weekdayStringFromDate:beginDate];

}




#pragma mark ---

#pragma mark --- 初始化

- (NSTimeZone*)timeZone

{

if (_timeZone == nil) {

[UIColor blueColor];

_timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];

}

return _timeZone;

}

- (NSArray*)weekdays

{

if (_weekdays == nil) {

_weekdays = [NSArray arrayWithObjects: [NSNull null], @"0", @"1", @"2", @"3", @"4", @"5", @"6", nil];

}

return _weekdays;

}

- (NSCalendar*)calender

{

if (_calender == nil) {

_calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

}

return _calender;

}

- (NSDateComponents*)comps

{

if (_comps == nil) {

_comps = [[NSDateComponents alloc] init];

}

return _comps;

}

- (NSDateFormatter*)formatter

{

if (_formatter == nil) {

_formatter =[[NSDateFormatter alloc]init];

[_formatter setDateFormat:@"yyyy-MM-dd"];

}

return _formatter;

}

你可能感兴趣的:(各种时间获取)