iOS支付技术iOS Developerios实用开发技巧

iOS 获取时间(戳)及差值

2017-06-13  本文已影响111人  南城同學
一、获取时间
1.获取当前时间
+ (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间
    NSString *currentDate = [formatter stringFromDate:datenow];
    return currentDate;
}
2.获取两个时间的间隔
/**持续时间*/
+ (long long)getDurationStartTime:(NSString *)startTime endTime:(NSString *)endTime {
    if (startTime && endTime) {
        NSDateFormatter *strDateStr = [[NSDateFormatter alloc]init];
        [strDateStr setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
        NSDate *startdate = [strDateStr dateFromString:startTime];
        NSDate *enddate = [strDateStr dateFromString:endTime];
        //时间转时间戳的方法:
        NSTimeInterval aTime = [enddate timeIntervalSinceDate:startdate];
        return (long long)aTime;
    } else {
        return -1;
    }
}

二、时间戳
1.获取当前时间戳
+ (NSString *)getCurrentTimeStamp {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间
    
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[datenow timeIntervalSince1970]] integerValue];
    NSString *ts = [NSString stringWithFormat:@"%ld",(long)timeSp];//时间戳的值
    return ts;
}

2、时间戳取差值
/**持续时间*/
+ (long long)getDurationStartTime:(NSString *)startTime endTime:(NSString *)endTime {
    if (startTime && endTime) {
        long long aTime = [endTime longLongValue] - [startTime longLongValue];
        return aTime;
    } else {
        return -1;
    }
}

上一篇下一篇

猜你喜欢

热点阅读