版本
Xcode 8.2.1
没什么可说的,直接上代码吧。注意实例化日期解析器和设置它的格式。等到后面写到UI篇的时候再提及。
int main(int argc, char * argv[]) {
//时间戳:计算机元年(1970年1月1日)距离当前时间的总秒数
//服务器给时间时(如截止日期),最好给时间戳,比较好处理
//日期解析器:将日期按某种格式输出
//默认时区:格林威治标准时间GMT
//获取计算机当前的时间(GMT)
NSDate *currentDate = [NSDate date];
NSLog(@"格林威治标准时间GMT:%@",currentDate);
//日期解析器
NSDateFormatter *dateFormatter = [NSDateFormatter new];
//设置时区
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Beijing"];
// dateFormatter.timeZone = [NSTimeZone systemTimeZone]; //与设备系统时区一致
//设置日期格式
dateFormatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
//可删掉不需要的,“-”可换成其他字符,如“:”
dateFormatter.dateFormat = @"YYYY:MM:dd HH:mm:ss";
//把NSDate对象转换成字符串输出
NSString *dateStr = [dateFormatter stringFromDate:currentDate];
NSLog(@"当前北京时间:%@",dateStr);
//把字符串转换成NSDate对象
NSDate *distanceDate = [dateFormatter dateFromString:@"2033:03:03 15:33:33"]; //格式需与之前设置的dateFormat一样
if (distanceDate) {
//转换成功
//计算两个时间相差的总秒数
NSInteger seconds = [currentDate timeIntervalSinceDate:distanceDate];
NSLog(@"剩余%ld天%ld小时%ld分%ld秒到期",seconds/(3600*24),seconds%(3600*24)/3600,seconds%3600/60,seconds%60);
//距离现在的时间
NSInteger seconds1 = distanceDate.timeIntervalSinceNow;
NSLog(@"距离现在有%ld秒",(long)seconds1);
//距离1970年时间
NSInteger seconds2 = distanceDate.timeIntervalSince1970;
NSLog(@"距离1970年有%ld秒",(long)seconds2);
}
}
我的结果:
网友评论