1:根据输入的时间的到星期几(2017-2-22)-(星期三)
-(NSString *)getTheDayOfTheWeekByDateString:(NSString *)dateString{
NSDateFormatter *inputFormatter=[[NSDateFormatter alloc]init];
[inputFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *formatterDate=[inputFormatter dateFromString:dateString];
NSDateFormatter *outputFormatter=[[NSDateFormatter alloc]init];
outputFormatter.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh"];//中文(星期三)
// outputFormatter.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];//默认:英文(Wednesday)
[outputFormatter setDateFormat:@"EEEE-MMMM-d"];
NSString *outputDateStr=[outputFormatter stringFromDate:formatterDate];
NSArray *weekArray=[outputDateStr componentsSeparatedByString:@"-"];
return [weekArray objectAtIndex:0];
}
NSLog(@"今天是- %@", [self getTheDayOfTheWeekByDateString:@"2017-2-22"]);
输出:今天是-星期三。
2判断时间
//根据字符串的到一个时间-->调用判断时间方法。
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd";
NSDate *dd = [fmt dateFromString:@"2016-2-22"];
NSLog(@"%d",[dd isThisYear]);
/** 比较from和self的时间差值*/
- (NSDateComponents *)deltaFrom:(NSDate *)from {
NSCalendar *calendar = [NSCalendar currentCalendar];// 日历
// 比较时间
NSCalendarUnit unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
return [calendar components:unit fromDate:from toDate:self options:0];
}
/**是否为今年*/
- (BOOL)isThisYear {
NSCalendar *calendar = [NSCalendar currentCalendar];// 日历
NSInteger nowYear = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
NSInteger selfYear = [calendar component:NSCalendarUnitYear fromDate:self];
return nowYear == selfYear;
}
/**是否为今天*/
- (BOOL)isToday {
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd";
NSString *nowString = [fmt stringFromDate:[NSDate date]];
NSString *selfString = [fmt stringFromDate:self];
return [nowString isEqualToString:selfString];
}
/**是否为昨天*/
- (BOOL)isYesterday {
// 2016-12-31 23:59:59 -> 2016-12-31
// 2017-01-01 00:00:01 -> 2017-01-01
// 日期格式化类
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"yyyy-MM-dd";
NSDate *nowDate = [fmt dateFromString:[fmt stringFromDate:[NSDate date]]];
NSDate *selfDate = [fmt dateFromString:[fmt stringFromDate:self]];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *cmps = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:selfDate toDate:nowDate options:0];
return cmps.year == 0
&& cmps.month == 0
&& cmps.day == 1;
}
常用的时间格式有iOS NSDateFormatter日期时间格式处理的用法
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd
MM dd yyyy
待补充:
3