iOS NSDate常用方法

 //时间戳转时间的方法.  时间戳 1368082020. 转 2018/06/23 转换格式自己定
+ (NSString *)getTimeStrByTimeSp:(NSString *)timeStamp format:(NSString *)timeFormat{
    //时间戳转时间的方法
    timeStamp = [timeStamp substringToIndex:10];
    NSTimeInterval time2 =[timeStamp doubleValue];
    NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:time2];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:timeFormat];
    NSString *currentTime = [formatter stringFromDate:date2];
    return currentTime;
}
//使用  这里把你要格式化的时间格式传给它  timeString是时间戳
    NSString *timeString = [NSString stringWithFormat:@"%ld",model.examTime];
    NSString *dateString = [NSDate getTimeStrByTimeSp:timeString format:@"yyyy/MM/dd"];

//服务器时间 1368082020 时间戳 转NSDate

      NSString *serviceString = [NSDate getTimeStrByTimeSp:serverTime format:@"YYYY-MM-dd HH:mm:ss"];
      NSLocale *CurrenLocale = [NSLocale currentLocale];
      NSTimeZone *localZone = [NSTimeZone timeZoneWithName:@"UTC"];
      NSDate *serverDate = [NSDate dateWithString:serviceString format:@"YYYY-MM-dd HH:mm:ss" timeZone:localZone locale:CurrenLocale];
      ```

NSDate分类方法

+ (NSDate *)dateWithString:(NSString *)dateString format:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    if (timeZone) [formatter setTimeZone:timeZone];
    if (locale) [formatter setLocale:locale];
    return [formatter dateFromString:dateString];
}
 //开始时间

//时间字符串2018-11-16 20:15:33 转NSDate.

NSDate *seckillDate = [NSDate dateWithString:exchangeListInfo.seckillStartTime format:@"YYYY-MM-dd HH:mm:ss" timeZone:localZone locale:CurrenLocale];
//NSDate分类方法
+ (NSDate *)dateWithString:(NSString *)dateString format:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    if (timeZone) [formatter setTimeZone:timeZone];
    if (locale) [formatter setLocale:locale];
    return [formatter dateFromString:dateString];
}
//时间相减
NSTimeInterval futureTimeInterval = [seckillDate timeIntervalSinceDate:serverDate];

你可能感兴趣的:(iOS NSDate常用方法)