时间戳
ios 在webView中的网页中,时间戳使用时(js)格式要用/ 而不能是-
如 应该使用2018/09/07,而不是2018-07-09
时间戳的使用和获取
- 根据时间string获取时间戳
//根据时间string获取时间戳
NSString *startTime = [_sessionArray[indexPath.row] objectForKey:@"talktime"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
NSDate *startDate = [formatter dateFromString:startTime];
NSUInteger startStamp = [startDate timeIntervalSince1970];
- 获取当前时间戳
//获取当前时间戳
NSDate *nowDate = [NSDate date];
NSUInteger nowStamp = [nowDate timeIntervalSince1970];
- 根据时间获取倒计时并显示
if (nowStamp < startStamp) {
[self startTimerWithSeconds:startStamp - nowStamp endBlock:^{
//time 倒计时显示时间
NSString *time = [self timeBeforeInfoWithString:startStamp];
}];
}
// 根据时间戳进行倒计时
- (void)startTimerWithSeconds:(long)seconds endBlock:(void(^)(void))endBlock
{
__block long timeout = seconds;//倒计时时间
dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_source_t _timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0,queue);
dispatch_source_set_timer(_timer,dispatch_walltime(NULL,0),1.0*NSEC_PER_SEC,0);//每秒执行
dispatch_source_set_event_handler(_timer, ^{
if(timeout < 0){ //倒计时结束,回调block
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
// 主线程处理
});
}else{
timeout -= 1;
dispatch_async(dispatch_get_main_queue(), ^{
if(endBlock) {
endBlock();
}
});
}
});
dispatch_resume(_timer);
}
//倒计时显示格式 (剩余时间)
- (NSString *)timeBeforeInfoWithString:(NSTimeInterval)timeIntrval{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//获取此时时间戳长度
NSTimeInterval nowTimeinterval = [[NSDate date] timeIntervalSince1970];
int timeInt = timeIntrval - nowTimeinterval; //时间差
int year = timeInt / (3600 * 24 * 30 *12);
int month = timeInt / (3600 * 24 * 30);
int day = timeInt / (3600 * 24);
int hour = timeInt % (3600 * 24) / 3600;
int minute = timeInt % (3600 * 24) % 3600 / 60;
int second = timeInt % (3600 * 24) % 3600 % 60;
if (year > 0) {
return [NSString stringWithFormat:@"%d年后",year];
}else if(month > 0){
return [NSString stringWithFormat:@"%d个月后",month];
}else if(day > 0){
return [NSString stringWithFormat:@"%d天%02d:%02d:%02d", day, hour, minute, second];
}else if(hour > 0){
return [NSString stringWithFormat:@"%02d:%02d:%02d", hour, minute, second];
}else if(minute > 0){
return [NSString stringWithFormat:@"%02d:%02d",minute, second];
}else{
return [NSString stringWithFormat:@"%02d", second];
}
}
网友评论