// 今天几号
- (NSInteger)day:(NSDate *)date{
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
return [components day];
}
// 今天几月
- (NSInteger)month:(NSDate *)date{
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
return [components month];
}
// 那年
- (NSInteger)year:(NSDate *)date{
NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
return [components year];
}
// 每月的第一天是周几
- (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
[comp setDay:1];
NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
return firstWeekday - 1;
}
// 这个月天数
- (NSInteger)totaldaysInThisMonth:(NSDate *)date{
NSRange totaldaysInMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
return totaldaysInMonth.length;
}
//NSString转NSDate
- (NSDate *)dateFromString:(NSString *)dateString
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setDateFormat: @"yyyy-MM"];
NSDate *destDate= [dateFormatter dateFromString:dateString];
return destDate;
}
//NSDate转NSString
- (NSString *)stringFromDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *destDateString = [dateFormatter stringFromDate:date];
return destDateString;
}
// 时间格式
-(NSString*)time:(NSString*)num{
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
[inputFormatter setDateFormat:@"yyyyMMdd"];
NSDate* inputDate = [inputFormatter dateFromString:num];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[NSLocale currentLocale]];
[outputFormatter setDateFormat:@"yyyy年MM月dd日"];
NSString *str = [outputFormatter stringFromDate:inputDate];
return str;
}