1.先在类目里定义这俩个变量
{
NSDateFormatter *_dataFormater;
NSDate *_date;
}
2.在viewDidLoad里面写这段代码
_dataFormater = [[NSDateFormatter alloc] init];
[_dataFormater setDateFormat:@"HH:mm:ss"];
[_dataFormater setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
//时间格式设置完成
// test curent time
// NSTimeInterval timer = [NSDate dateWithTimeIntervalSince1970:];
// NSTimeInterval timer = [[NSDate date] timeIntervalSinceReferenceDate];
//直接从date得到时间格式 与实际时间相差8小时
NSString *stringFromNowDate = [_dataFormater stringFromDate:[NSDate date]];
NSLog(@"stringFromNowDate : %@", stringFromNowDate);
// 输出: 15:29:37 显示时间: 23:29 差8小时
// solve workable solution
_date = [NSDate date];
NSLog(@"date :%@", _date);
NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
NSInteger intetval = [timeZone secondsFromGMTForDate:_date];
NSLog(@"intetval :%d", intetval);// 28800
//现在时间
NSDate *localDate = [_date dateByAddingTimeInterval:intetval];
NSLog(@"localDate :%@", localDate);
NSString *stringFromLocal = [_dataFormater stringFromDate:localDate];
NSLog(@"stringFromLocal : %@", stringFromLocal);
NSDate *date1 = [_dataFormater dateFromString:@"23:47:10"];
NSLog(@"date1: %@", date1);
// nsdate是一个对象类型,日期时间格式很完整的,只是用于程序处理数据或者显示时不方便,因为一般ios处理的数据对象都是NSString,NSArray,NSDictionary。最好的办法把nsdate这种日期对象转化成其中的一种,苹果开发者文档提供了转化格式类NSDateFormatter专门进行NSString和NSDate的互相转化,
// NSTimeInterval是一个简单数据类型 的重命名 double醒数据 用户NSDate使用 表示距离某个日期多少秒 或者某个日期距离什么时间点多少秒 时间戳就是指这个数据。一般是距离1970年的时间距离。有可能是毫秒有可能是秒,这个要看具体服务器返回,这个诗句返回的是秒
3.在一个button点击事件里写这段代码:
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:[NSDate date]];
NSDate *localDate = [NSDate dateWithTimeInterval:interval sinceDate:[NSDate date]];
NSLog(@"clicled localDate :%@\nlocalDate.description:%@", localDate, localDate.description);
NSString *string = [_dataFormater stringFromDate:localDate];
NSLog(@"%@", string);
//假如这是俩个时间时间差
NSTimeInterval interval1 = 28800;
NSTimeInterval interval2 = [[NSDate date] timeIntervalSinceDate:_date];
NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:interval1];
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:interval2];
NSLog(@"date1 :%@", date1);
NSLog(@"data2 : %@", date2);
NSString *intervalTime1 = [_dataFormater stringFromDate:date1];
NSString *intervalTime2 = [_dataFormater stringFromDate:date2];
NSLog(@"interval1 : %@", intervalTime1);
NSLog(@"interval2 : %@", intervalTime2);
不准确确的欢迎指正。