iOS 时间转化相关

2019-05-28  本文已影响0人  风___________

将年月日转化为字符串(eg:2012 2 3 -> 20120203)

+ (long)padByYear:(long)year AndMonth:(long)month AndDay:(long)day{
    return [[self getStringByYear:year AndMonth:month AndDay:day] longLongValue];
}
+ (NSString *)getStringByYear:(long)year AndMonth:(long)month AndDay:(long)day{
    NSString *(^pad)(long value) = ^(long value){
        return value < 10?[NSString stringWithFormat:@"0%ld",value]:[NSString stringWithFormat:@"%ld",value];
    };
    return [NSString stringWithFormat:@"%ld,%@,%@",year,pad(month),pad(day)];
}

判断年月日是否为周一

+ (BOOL)isMondayByYear:(long)year AndMonth:(long)month AndDay:(long)day{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    NSDate *date = [dateFormatter dateFromString:[self getStringByYear:year AndMonth:month AndDay:day]];
    return ([[[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:date] weekday]) == 2;
}

年月日转化为date对象

+ (NSDate *)DateByYear:(long)year AndMonth:(long)month AndDay:(long)day{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    NSDate *date = [dateFormatter dateFromString:[self getStringByYear:year AndMonth:month AndDay:day]];
    return date;
}

timeIntervalSince1970转化为年月日 (eg:20190902)

+ (long)padByTimeIntervalSince1970:(NSTimeInterval)time{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    return [[dateFormatter stringFromDate:date] longLongValue];
}

判断年月日是否合法


// 判断年月日是否合法
+ (BOOL)isValidityDateByYear:(long)year AndMonth:(long)month AndDay:(long)day{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    NSDate *date = [dateFormatter dateFromString:[self getStringByYear:year AndMonth:month AndDay:day]];
    if (!date) return NO;
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
    return ([components day] == day);
}

判断年月日是否为周末

// 判断年月日是否为周末
+ (BOOL)isWeekendByYear:(long)year AndMonth:(long)month AndDay:(long)day{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    NSDate *date = [dateFormatter dateFromString:[self getStringByYear:year AndMonth:month AndDay:day]];
    long weekday = [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:date] weekday];
    return weekday == 7 || weekday == 1;
}
上一篇下一篇

猜你喜欢

热点阅读