IOS日期处理

一、先定义一个全局变量的NSTimeInterval

复制代码

@interface ViewController ()

{

NSTimeInterval timeInterVal;

}

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

timeInterVal = 8*60*60;

[self createDateObject];

}

复制代码

获取世界标准时间,比中国时间早八个小时

1  NSDate *date = [NSDate date];

2    NSLog(@"%@",date);

从现在世界标准的时间 往后推timeInterVal后的时间(如果timeInterVal是负数就是往前推)

NSDate *sinceNowDate = [NSDate dateWithTimeIntervalSinceNow:timeInterVal];

NSLog(@"%@",sinceNowDate);

计算机时间1970-01-01 00:00:00 往后退timeInterVal八小时后的时间(为负数则往前)

NSDate *since1970 = [NSDate dateWithTimeIntervalSince1970:timeInterVal];

NSLog(@"%@",since1970);

从自定义的时间往后推八个小时 date是自定义的时间  timeInterVal是推迟的时间

NSDate *sinceCustomDate = [NSDate dateWithTimeInterval:timeInterVal sinceDate:date];

NSLog(@"%@",sinceCustomDate);

从2001-01-01 00:00:00 开始往后推八个小时

NSDate *since2001 = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterVal];

NSLog(@"%@",since2001);

永远不可能达到的一个时间点

NSDate *futureDate = [NSDate distantFuture];

NSLog(@"%@",futureDate);

一个无限过去的时间点

NSDate *pastDate = [NSDate distantPast];

NSLog(@"%@",pastDate);

二、时间差计算

从计算机时间1970-01-01 00:00:00到date日期的时间差

NSLog(@"%f",date.timeIntervalSince1970);

从计算机时间2001-01-01 00:00:00到newDate日期的时间差

NSDate *newDate = [NSDate date];

NSLog(@"%f",newDate.timeIntervalSinceReferenceDate);

从当前时间到newDate的时间差

NSLog(@"%f",newDate.timeIntervalSinceNow);

已知两个时间戳  比较两个日期的早晚

1451047216    1451847216

复制代码

NSDate *oneDate = [NSDate dateWithTimeIntervalSince1970:1451047216];

NSDate *anotherDate = [NSDate dateWithTimeIntervalSince1970:1451847216];

NSDate *earlyDate = [oneDate earlierDate:anotherDate];

NSLog(@"较早的:%@",earlyDate);

NSDate *laterDate = [oneDate laterDate:anotherDate];

NSLog(@"较晚的日期:%@",laterDate);

//    获得两个日期的时间差

NSTimeInterval timer = [oneDate timeIntervalSinceDate:anotherDate];

NSLog(@"%f",timer);

复制代码

三、日期格式器

复制代码

y  年

M  年中的月份

D  当天是今年的第多少天

d  月份中的天数

F  月份中的周数

E  星期几

a  Am/pm

H  一天中的小时数(0-23)

k  一天中的小时数(1-24)

K  am/pm 中的小时数(0-11)  Number  0

h  am/pm 中的小时数(1-12)  Number  12

m  小时中的分钟数  Number  30

s  分钟中的秒数  Number  55

S  毫秒数  Number  978

z  时区  General time zone  Pacific Standard Time; PST; GMT-08:00

Z  时区  RFC 822 time zone  -0800

复制代码

复制代码

//    日期格式器

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

formatter.dateFormat = @"yyyy-MM-dd hh:mm:ss";

//

NSString *dateString = [formatter stringFromDate:date];

NSLog(@"%@",dateString);

//    把字符串转换成日期

NSDate *stringDate = [formatter dateFromString:dateString];

NSLog(@"%@",stringDate);

复制代码

注意:在实际项目中

如果你用的时间戳是后台给你传过来的话,要记得核查是否该时间戳是否乘以1000。根据情况来决定是否除以1000。如果乘以过1000,表明后台给你传过来的是毫秒。

你可能感兴趣的:(IOS日期处理)