#import <Foundation/Foundation.h>
@interface NSDate (Addition)
/**
*某一天在当月多少号
*/
- (NSInteger)daysOfCurrentMonth;
/**
* 某月第一天周几
*
*/
- (NSInteger)weekOfFirstDayInCurrentMonth;
- (NSInteger)day;
- (NSInteger)month;
- (NSInteger)year;
- (NSString *)dateStrWithFormat:(NSString *)format;
- (NSTimeInterval)zeroTimestamp;
@end
#import "NSDate+Addition.h"
@implementation NSDate (Addition)
- (NSInteger)daysOfCurrentMonth
{
NSInteger days = 0;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
days = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self].length;
return days;
}
- (NSInteger)weekOfFirstDayInCurrentMonth
{
NSInteger week = 0;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
week = [calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitWeekOfMonth forDate:self] - 1;
return week;
}
- (NSInteger)day
{
NSInteger day = 1;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
day = [calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self];
return day;
}
- (NSInteger)month
{
NSInteger month = 1;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
month = [calendar ordinalityOfUnit:NSCalendarUnitMonth inUnit:NSCalendarUnitYear forDate:self];
return month;
}
- (NSInteger)year
{
NSInteger year = 2015;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
year = [calendar ordinalityOfUnit:NSCalendarUnitYear inUnit:NSCalendarUnitEra forDate:self];
return year;
}
- (NSString *)dateStrWithFormat:(NSString *)format
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = format;
return [formatter stringFromDate:self];
}
- (NSTimeInterval)zeroTimestamp
{
NSTimeInterval timeInterval = 0;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd";
NSString *zeroTimeStr = [formatter stringFromDate:self];
NSDate *zeroDate = [formatter dateFromString:zeroTimeStr];
timeInterval = [zeroDate timeIntervalSince1970];
return timeInterval;
}
在制作日历是时间的分类尤其重要.