iOS常用时间工具

NSDate分类 .h


@interface NSDate (Common)

// 打印当前时间,精确到毫秒,主要用于调试
+ (void)printTimeToLog;

/// 传入时间是否是今年
/// @param timeStr yyyy-MM-dd HH:mm:ss
- (BOOL)isThisYear:(NSString *)timeStr;

//是否是本月
- (BOOL)isThisMonth:(NSString *)timeStr;

/**
 * 是否为今年
 */
- (BOOL)isThisYear;
/**
 *  是否为今天
 */
- (BOOL)isToday;

/**
 * 判断是不是本星期
 */
- (BOOL)isThisWeak;


//获得当前的时间戳唯一id字符串
+ (NSString *)getUniqueIdString;

//获得当前的时间戳唯一id字符串(整型)
+ (NSString *)getUniqueId_integerStr;

//获得当前的时间戳唯一id数字
+ (NSInteger)getUniqueId;

/// 获取详细的日期信息 yyyy-MM-dd HH:mm:ss 星期五
/// @param hms 显示时分秒 默认不显示
/// @param forDate 当前时间date
+ (NSString *)getDateTimehashms:(BOOL)hms currentDate:(NSDate *)forDate;

+ (NSString *)GetTimeText:(NSDate *)currentDate;

//当前时间获取星期几
+ (NSString *)weekdayStringFromDate:(NSDate *)inputDate;

// 本地化显示时间:如 en_US: 07/29/2018(只显示年日月)
+ (NSString *)getDateShowStr;
// 本地化显示时间:如 en_US: 07/29/2018(只显示年日月)
+ (NSString *)getDateShowStrWithDate:(NSDate *)date;

// 字符串时间转Date实例
+ (NSDate *)getDateWithTimeStr:(NSString *)timeStr format:(NSString *)format;

// 获取当前时间格式化  yyyy-MM-dd HH:mm
- (NSString *)getFormatStr:(NSString *)formatStr;

//时间戳转为时间格式
- (NSString *)dateAfterTimestamp:(NSInteger )timeStamp stringWithFormat:(NSString *)format;

//通过时间戳比对是否是今天
- (BOOL)timeisTodayInterval:(NSInteger)timeInterval formatBlcok:(void (^)(NSString *))format;


/**
*  计算时间戳相差当前时间天数
*  lastTime    时间戳 字符串

*/
+ (NSInteger)getDaysFrom:(NSString *)lastTime;
/**
*  计算2个日期相差天数

*  startDate  起始日期
*  endDate    截至日期

*/

+ (NSInteger)daysFromDate:(NSDate *)startDate toDate:(NSDate *)endDate;

/**
*  计算2个时间戳相差天数

*  startInterval  起始时间戳
*  endDate    截至时间戳 (当前时间戳)

*/

+ (NSInteger)daysFromInterval:(NSInteger )startInterval toInterval:(NSInteger )endInterval;

@end

.m类


@implementation NSDate (Common)


/**
 *  是否为今天
 */
- (BOOL)isToday {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear;
    
    // 1.获得当前时间的年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
    
    // 2.获得self的年月日
    NSDateComponents *selfCmps = [calendar components:unit fromDate:self];
    return
    (selfCmps.year == nowCmps.year) &&
    (selfCmps.month == nowCmps.month) &&
    (selfCmps.day == nowCmps.day);
}

//获得当前的时间戳唯一id字符串
+ (NSString *)getUniqueIdString{
    
    static CGFloat addNum = 1000.f;
    
    NSString *dateString = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] + addNum + arc4random_uniform(1000)];
    addNum++;
    return dateString;
}

//获得当前的时间戳唯一id字符串(整型)
+ (NSString *)getUniqueId_integerStr{
    
    NSDate *fixedDate = [NSDate date];
    long utcTime = fixedDate ? fixedDate.timeIntervalSince1970 : time(NULL);
    NSString *dateString = [NSString stringWithFormat:@"%ld",utcTime + arc4random_uniform(1000000)];
    return dateString;
}

//获得当前的时间戳唯一id数字
+ (NSInteger)getUniqueId{
   
    static CGFloat addNumber = 1000;
    addNumber++;
    return [[NSDate date] timeIntervalSince1970] + addNumber;
}

+ (void)printTimeToLog{
    
    NSLog(@"当前时间:%@",[[self date] getFormatStr:@"yyyy-MM-dd HH:mm:ss:SSS"]);
}

+ (NSString *)getDateTimehashms:(BOOL)hms currentDate:(NSDate *)forDate{
    if (forDate == nil) {
        return @"";
    }
    NSString * language = [self getPreferredLanguage];
    
    //获取日期
    NSArray * arrWeek;
    
    //获取日期
    if ([language isEqualToString:@"zh-Hans-CN"]||[language isEqualToString:@"zh-Hans"]) {
        
        arrWeek=[NSArray arrayWithObjects:@"星期日",@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六",nil];
    }else{
        arrWeek=[NSArray arrayWithObjects:@"Sunday",@"Monday",@"Tuesday",@"Wednesday",@"Thursday",@"Friday",@"Saturday",nil];
    }
    
    //获取当前日期
    NSDate *date = forDate;
    
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    //设置时区
    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"ZH_cn"];
  
    NSInteger unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |
    NSCalendarUnitDay |
    NSCalendarUnitWeekday |
    NSCalendarUnitHour |
    NSCalendarUnitMinute |
    NSCalendarUnitSecond;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    NSInteger week0 = [comps weekday];
    NSInteger year0 =[comps year];
    NSInteger month0 = [comps month];
    NSInteger day0 = [comps day];
    
    NSString *str;
    if (hms) {
        //时分秒
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"aahh:mm:ss"];
        NSString *currentDateStr = [dateFormatter stringFromDate:forDate];
        
        if ([language isEqualToString:@"zh-Hans-CN"]||[language isEqualToString:@"zh-Hans"]) {
            
            str = [NSString stringWithFormat:@" %ld年%ld月%ld日 %@  %@ ",(long)year0,(long)month0,(long)day0,[arrWeek objectAtIndex:(week0 - 1)],currentDateStr];
        }else{
            str = [NSString stringWithFormat:@" %ld-%02ld-%02ld %@  %@ ",(long)year0,(long)month0,(long)day0,[arrWeek objectAtIndex:(week0 - 1)],currentDateStr];
        }
    }else {
       
        if ([language isEqualToString:@"zh-Hans-CN"]||[language isEqualToString:@"zh-Hans"]) {
            
            str = [NSString stringWithFormat:@"%ld年%ld月%ld日 %@",(long)year0,(long)month0,(long)day0,[arrWeek objectAtIndex:(week0 - 1)]];
        }else{
            str = [NSString stringWithFormat:@"%ld-%02ld-%02ld %@",(long)year0,(long)month0,(long)day0,[arrWeek objectAtIndex:(week0 - 1)]];
        }
    }
  
    return str;
}

//当前时间获取星期几
+ (NSString *)weekdayStringFromDate:(NSDate *)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    /*
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //自定义月份显示
        dateFormatter.monthSymbols = @[@"一", @"二", @"三", @"四", @"五", @"六", @"七", @"八", @"九", @"十", @"十一", @"十二"];
        //自定义星期显示
        dateFormatter.weekdaySymbols = @[@"星期日", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六"];
        //自定义日期显示
        dateFormatter.dateFormat = @"yyyy年 MMMM月 dd日 EEEE";
        NSString *dateStr = [dateFormatter stringFromDate:[NSDate date]];
        NSLog(@"%@", dateStr);
     */
}


+ (NSDate *)getDateWithTimeStr:(NSString *)timeStr format:(NSString *)format{
    
    /* 常用的格式
    @"yyyy-MM-dd"
    yyyy-MM-dd HH:mm:ss.SSS
    yyyy-MM-dd HH:mm:ss
    yyyy-MM-dd
    MM dd yyyy
     */
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    //[inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:format];
    NSDate * inputDate = [inputFormatter dateFromString:timeStr];
    
    return inputDate;
}

+ (NSInteger)compareDate:(NSString*)aDate withDate:(NSString*)bDate{
    
    NSInteger aa;
    NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];
    [dateformater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSDate *dta = [[NSDate alloc] init];
//    NSDate *dtb = [[NSDate alloc] init];
    
    NSDate *dta = [dateformater dateFromString:aDate];
    NSDate *dtb = [dateformater dateFromString:bDate];
    NSComparisonResult result = [dta compare:dtb];
    if (result == NSOrderedSame){
        //相等
        aa = 0;
    }else if (result == NSOrderedAscending){
        //bDate比aDate大
        aa = 1;
    }else {
        //bDate比aDate小
        aa = -1;
    }
    
    return aa;
}


+ (NSString *)GetTimeText:(NSDate *)currentDate{
    
    NSString * language = [self getPreferredLanguage];
    
    //获取当前日期
    NSDate *date = currentDate;
    
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    //设置时区
    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];

    NSInteger unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |
    NSCalendarUnitDay |
    NSCalendarUnitWeekday |
    NSCalendarUnitHour |
    NSCalendarUnitMinute |
    NSCalendarUnitSecond;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    NSInteger year0 =[comps year];
    NSInteger month0 = [comps month];
    NSInteger day0 = [comps day];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"aahh:mm:ss"];
    
    NSString *str;
    
    if ([language isEqualToString:@"zh-Hans-CN"]||[language isEqualToString:@"zh-Hans"]) {
        
        str = [NSString stringWithFormat:@"%ld年%ld月%ld日",(long)year0,(long)month0,(long)day0];
    }else{
        str = [NSString stringWithFormat:@"%ld/%02ld/%02ld",(long)year0,(long)month0,(long)day0];
    }
    return str;
}

/**
 *得到本机现在用的语言
 * en-CN 或en  英文  zh-Hans-CN或zh-Hans  简体中文   zh-Hant-CN或zh-Hant  繁体中文    ja-CN或ja  日本  ......
 */
+ (NSString*)getPreferredLanguage
{
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSString* preferredLang = [languages objectAtIndex:0];
    return preferredLang;
}

- (NSString *)getFormatStr:(NSString *)formatStr{
    
    // 实例化NSDateFormatter
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // 设置日期格式 比如:@"yyyy-MM-dd HH:mm:ss"
    [formatter setDateFormat:formatStr];
    // 获取当前日期
    NSString *currentDateString = [formatter stringFromDate:self];
    
    return currentDateString;
}

// 本地化显示时间:如 en_US: 07/29/2018(只显示年日月)
+ (NSString *)getDateShowStr{
    return [self getDateShowStrWithDate:[self date]];
}
// 本地化显示时间:如 en_US: 07/29/2018(只显示年日月)
+ (NSString *)getDateShowStrWithDate:(NSDate *)date{
    
    NSString *dateComponents = @"yyyy-MM-dd";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *locale = [NSLocale autoupdatingCurrentLocale];
    
    [dateFormatter setLocale:locale];
    NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];
    [dateFormatter setDateFormat:dateFormat];
    return [dateFormatter stringFromDate:date];
}


- (NSString *)dateAfterTimestamp:(NSInteger )timeStamp stringWithFormat:(NSString *)format {
    
    NSTimeInterval afterTime = timeStamp;
    NSDate *dete = [[NSDate alloc] initWithTimeIntervalSince1970:afterTime];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    NSString *dateStr = [formatter stringFromDate:dete];
    return dateStr;
}

//通过时间戳比对是否是今天
- (BOOL)timeisTodayInterval:(NSInteger)timeInterval formatBlcok:(void (^)(NSString *))format{
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    formatter.dateFormat = @"yyyy-MM-dd HH:mm";
    NSString *timeStr = [formatter stringFromDate:date];
     if (format) {
         format(timeStr);
     }
    if (date.isToday) {
        //是今天
        return YES;
    }else {
        return NO;
    }
    
}

//判断是不是本星期
- (BOOL)isThisWeak{
    // 日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitWeekday | NSCalendarUnitMonth | NSCalendarUnitYear | kCFCalendarUnitDay | kCFCalendarUnitHour | kCFCalendarUnitMinute ;
    
    //1.获得当前时间的 年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];
    NSDateComponents *sourceCmps = [calendar components:unit fromDate:self];
    
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:[NSDate date] toDate:self options:0];
    NSInteger subDay = labs(dateCom.day);
    NSInteger subMonth = labs(dateCom.month);
    NSInteger subYear = labs(dateCom.year);
    
    if (subYear == 0 && subMonth == 0) { //当相关的差值等于零的时候说明在一个年、月、日的时间范围内,不是按照零点到零点的时间算的
        if (subDay > 6) { //相差天数大于6肯定不在一周内
            return NO;
        } else { //相差的天数大于或等于后面的时间所对应的weekday则不在一周内
            if (dateCom.day >= 0 && dateCom.hour >=0 && dateCom.minute >= 0) { //比较的时间大于当前时间
                //西方一周的开始是从周日开始算的,周日是1,周一是2,而我们是从周一开始算新的一周
                NSInteger chinaWeekday = sourceCmps.weekday == 1 ? 7 : sourceCmps.weekday - 1;
                if (subDay >= chinaWeekday) {
                    return NO;
                } else {
                    return YES;
                }
            } else {
                NSInteger chinaWeekday = sourceCmps.weekday == 1 ? 7 : nowCmps.weekday - 1;
                if (subDay >= chinaWeekday) { //比较的时间比当前时间小,已经过去的时间
                    return NO;
                } else {
                    return YES;
                }
            }
        }
    } else { //时间范围差值超过了一年或一个月的时间范围肯定就不在一个周内了
        return NO;
    }
}

- (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)isThisYear:(NSString *)timeStr
{
    // 日历
    NSDateComponents *comp = [self currentTime];
    NSArray *subDataArr = [timeStr componentsSeparatedByString:@"-"];
    NSString *monthStr = [subDataArr objectAtIndex:0];
    if (comp.year == [monthStr integerValue]) {
        return YES;
    }else {
        return NO;
    }
}

/**
 *  判断是不是本月
 *
 *  @return YES 是 NO 不是
 */
- (BOOL)isThisMonth:(NSString *)timeStr {
    
    return [self isSameMonthAsDate:timeStr];
}

- (BOOL)isSameMonthAsDate:(NSString *)timeStr {
    
    NSDateComponents *comp = [self currentTime];
    //将字符串切割成数组
    NSArray *subDataArr = [timeStr componentsSeparatedByString:@"-"];
    NSString *monthStr = [subDataArr objectAtIndex:1];
    if (comp.month == [monthStr integerValue]) {
        return YES;
    }else {
        return NO;
    }
}


- (NSDateComponents *)currentTime {
    
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDate* dt = [NSDate date];
    
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    
    NSDateComponents* comp = [gregorian components: unitFlags
                                          fromDate:dt];
    
    return comp;
}


/**
*  计算时间戳相差当前时间天数
*  lastTime    时间戳 字符串
*/
+ (NSInteger)getDaysFrom:(NSString *)lastTime {
    
    NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDate* fromdate = [NSDate dateWithTimeIntervalSince1970:[lastTime doubleValue] / 1000.0];
    
    NSDate* date = [NSDate date];
    
    [gregorian setFirstWeekday:2];
    
    NSDate *fromDate;
    
    NSDate *toDate;
    
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:fromdate];
    
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:NULL forDate:date];
    
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
    
    return dayComponents.day;
}



/**
*  计算2个日期相差天数
*  startDate  起始日期
*  endDate    截至日期
*/
+ (NSInteger)daysFromDate:(NSDate *)startDate toDate:(NSDate *)endDate {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // 话说在真机上需要设置区域,才能正确获取本地日期,中国代码:zh_CN
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //得到相差秒数
    NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
    
    int days = ((int)time)/(3600*24);
    
    int hours = ((int)time)%(3600*24)/3600;
    
    int minute = ((int)time)%(3600*24)/3600/60;
    
    if (days <= 0 && hours <= 0&&minute<= 0) {
        
        NSLog(@"0天0小时0分钟");
        return 0;
        
    } else {
        NSLog(@"%@",[[NSString alloc] initWithFormat:@"%i天%i小时%i分钟",days,hours,minute]);
        // 之所以要 + 1,是因为 此处的days 计算的结果 不包含当天 和 最后一天\
        //(如星期一 和 星期四,计算机 算的结果就是2天(星期二和星期三),日常算,星期一——星期四相差3天,所以需要+1)\
        //对于时分 没有进行计算 可以忽略不计
        return days + 1;
        
    }
    
}

/**
*  计算2个时间戳相差天数

*  startInterval  起始时间戳
*  endDate    截至时间戳 (当前时间戳)

*/

+ (NSInteger)daysFromInterval:(NSInteger )startInterval toInterval:(NSInteger )endInterval{
    
    //创建两个日期
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//    NSDate *startDate = [dateFormatter dateFromString:@"2021-01-06"];
//    NSDate *endDate = [dateFormatter dateFromString:@"2021-01-21"];

    NSDate* startDate = [NSDate dateWithTimeIntervalSince1970:startInterval]; //如果是毫秒级要 /1000.0
    NSDate *endDate = [NSDate date];
    
    if (endInterval > 0) {
        NSTimeInterval afterTime = endInterval;
        endDate = [[NSDate alloc] initWithTimeIntervalSince1970:afterTime];
    }
  
    
    //利用NSCalendar比较日期的差异
    NSCalendar *calendar = [NSCalendar currentCalendar];
    /**
     * 要比较的时间单位,常用如下,可以同时传:
     *    NSCalendarUnitDay : 天
     *    NSCalendarUnitYear : 年
     *    NSCalendarUnitMonth : 月
     *    NSCalendarUnitHour : 时
     *    NSCalendarUnitMinute : 分
     *    NSCalendarUnitSecond : 秒
     */
    NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
    //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:startDate toDate:endDate options:0];
    //打印
    NSLog(@"delta=%@",delta);
    //获取其中的"天"
    NSLog(@"相差=%ld",delta.day);
    return delta.day;
    
}


@end

你可能感兴趣的:(iOS常用时间工具)