NSDate 时间戳转字符串 ,字符串转NSDate,NSDate之间比较大小

时间戳转成字符串

  • (NSString )timeWithTimeIntervalString:(NSString )timeString
    format:(NSString )format {
    // 格式化时间
    NSDateFormatter
    formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    // 毫秒值转化为秒
    NSDate
    date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
    NSString
    dateString = [formatter stringFromDate:date];
    return dateString;

}

当前时间前几天数组

  • (NSArray *) timeWithBeforeTodayDays:(NSInteger)days {

    NSMutableArray *eightArr = [[NSMutableArray alloc] init];

    for (int i = 0; i < days; i ++) {
    //从现在开始的24小时
    NSTimeInterval secondsPerDay = -i * 246060;
    NSDate *curDate = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     [dateFormatter setDateFormat:@"M月d日"];
     NSString *dateStr = [dateFormatter stringFromDate:curDate];//几月几号
     [eightArr addObject:dateStr];
    

    }

    return eightArr;
    }
    获取当前时间
    +(NSString *)getCurrentDate{
    NSDate * date = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init ];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * dateStr = [dateFormatter stringFromDate:date];
    return dateStr;
    }

比较两个NSDate的大小

  • (BOOL)dataTransformTimestamp:(NSString)startDateStr endDate:(NSString)endStr{
    //将传入时间转化成需要的格式
    NSDateFormatter *format=[[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd"];
    [format setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];
    NSDate *startDate=[format dateFromString:startDateStr];
    NSDate *endDate=[format dateFromString:endStr];

    NSComparisonResult result = [startDate compare:endDate];

// NSLog(@"fromdate=%@",startDate);
//
// NSLog(@"enddate=%@",endDate);

if (result == NSOrderedDescending) {
    //NSLog(@"startDate  is in the future");
    return 1;
}
else if (result == NSOrderedAscending){
    //NSLog(@"startDate is in the past");
    return 0;
}
//NSLog(@"Both dates are the same");
return 0;

}

你可能感兴趣的:(NSDate 时间戳转字符串 ,字符串转NSDate,NSDate之间比较大小)