时间、时间戳相关小结 - iOS

650 阅读1分钟
项目中难免会与时间打交道,故此次围绕时间展开做了一些日常使用的小结;
如下 code 中也是围绕一些日常开发中较为常用的点展开小的方法封装.


具体方法的使用如下:

    // 2019-02-21 17:30:45 1550741445
    
    /** 当前时间戳*/
    NSString *timeInterval = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
    NSLog(@"当前时间戳: %@ --- 当前时间戳转时间: %@", timeInterval, YHIntervalToTime(timeInterval));
    NSLog(@"时间戳转换时间,时间格式自定义: %@", YHDateStringWithTimeInterval(timeInterval, @"yyy年MM月dd日 HH时mm分ss秒"));
    
    /** 日期格式*/
    NSString *dateFormat = @"yyyy-MM-dd HH:mm:ss";
    /** 当前时间 Str*/
    NSString *currentTime = YHGetCurrentTime(dateFormat);
    NSLog(@"当前时间: %@", currentTime);
    /** 当前时间 Date*/
    NSDate *currentDate = YHDateFromString(currentTime, dateFormat);
    NSLog(@"Str 转 Date: %@", currentDate);
    NSLog(@"Str 转 Date(自定义区域): %@", YHDateFromStringAndZone(currentTime, dateFormat, [NSTimeZone timeZoneWithAbbreviation:@"UTC"]));
    NSLog(@"Date 转 Str: %@", YHStringFromDate(currentDate, dateFormat));
    
    NSLog(@"时间日期转换 - 当前周: %@", YHNumDaysWeeks(currentDate));
    NSLog(@"时间日期转换 - 当前月: %@", YHNumDaysMonth(currentDate));
    
    NSDate *date = YHDateFromString(@"2019-02-21 17:30:45", dateFormat);
    if (!YHComparisonDateTimeIsOneDay(date, currentDate, dateFormat)) {
        NSLog(@"两时间不同");
        
        NSLog(@"指定时间距当前时间的时间差: %ld", (long)YHSpecifiesDifferenceBetweenTimeAndCcurrentTime(date));
        NSLog(@"时间差值计算(时间格式一样): %ld",
              (long)YHComparisonDateTimeDifference(date, currentDate, dateFormat));
    }

如上文中具体封装类在 GitHub 中的 YHUtility 类中.


以上便是此次小结的内容,还请大神多多指点!