IOS日期的处理
一、先定義一個(gè)全局變量的NSTimeInterval
@interface ViewController () {NSTimeInterval timeInterVal; } @end@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];timeInterVal = 8*60*60;[self createDateObject]; }獲取世界標(biāo)準(zhǔn)時(shí)間,比中國時(shí)間早八個(gè)小時(shí)
1 NSDate *date = [NSDate date]; 2 NSLog(@"%@",date);?從現(xiàn)在世界標(biāo)準(zhǔn)的時(shí)間 往后推timeInterVal后的時(shí)間(如果timeInterVal是負(fù)數(shù)就是往前推)
NSDate *sinceNowDate = [NSDate dateWithTimeIntervalSinceNow:timeInterVal];NSLog(@"%@",sinceNowDate);計(jì)算機(jī)時(shí)間1970-01-01 00:00:00 往后退timeInterVal八小時(shí)后的時(shí)間(為負(fù)數(shù)則往前)
?
NSDate *since1970 = [NSDate dateWithTimeIntervalSince1970:timeInterVal];NSLog(@"%@",since1970);?
??從自定義的時(shí)間往后推八個(gè)小時(shí) date是自定義的時(shí)間? timeInterVal是推遲的時(shí)間
NSDate *sinceCustomDate = [NSDate dateWithTimeInterval:timeInterVal sinceDate:date];NSLog(@"%@",sinceCustomDate);?從2001-01-01 00:00:00 開始往后推八個(gè)小時(shí)
NSDate *since2001 = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterVal];NSLog(@"%@",since2001);?永遠(yuǎn)不可能達(dá)到的一個(gè)時(shí)間點(diǎn)
NSDate *futureDate = [NSDate distantFuture];NSLog(@"%@",futureDate);一個(gè)無限過去的時(shí)間點(diǎn)
NSDate *pastDate = [NSDate distantPast];NSLog(@"%@",pastDate);二、時(shí)間差計(jì)算
從計(jì)算機(jī)時(shí)間1970-01-01 00:00:00到date日期的時(shí)間差
NSLog(@"%f",date.timeIntervalSince1970);從計(jì)算機(jī)時(shí)間2001-01-01 00:00:00到newDate日期的時(shí)間差
NSDate *newDate = [NSDate date]; NSLog(@"%f",newDate.timeIntervalSinceReferenceDate);從當(dāng)前時(shí)間到newDate的時(shí)間差
NSLog(@"%f",newDate.timeIntervalSinceNow);?已知兩個(gè)時(shí)間戳? 比較兩個(gè)日期的早晚
? ?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);// 獲得兩個(gè)日期的時(shí)間差NSTimeInterval timer = [oneDate timeIntervalSinceDate:anotherDate];NSLog(@"%f",timer);三、日期格式器
y? 年M? 年中的月份D? 當(dāng)天是今年的第多少天d? 月份中的天數(shù)F? 月份中的周數(shù)E? 星期幾a? Am/pmH? 一天中的小時(shí)數(shù)(0-23)k? 一天中的小時(shí)數(shù)(1-24)K? am/pm 中的小時(shí)數(shù)(0-11)? Number? 0h? am/pm 中的小時(shí)數(shù)(1-12)? Number? 12m? 小時(shí)中的分鐘數(shù)? Number? 30s? 分鐘中的秒數(shù)? Number? 55S? 毫秒數(shù)? Number? 978z? 時(shí)區(qū)? General time zone? Pacific Standard Time; PST; GMT-08:00Z? 時(shí)區(qū)? 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);// 把字符串轉(zhuǎn)換成日期NSDate *stringDate = [formatter dateFromString:dateString];NSLog(@"%@",stringDate);?
注意:在實(shí)際項(xiàng)目中
如果你用的時(shí)間戳是后臺(tái)給你傳過來的話,要記得核查是否該時(shí)間戳是否乘以1000。根據(jù)情況來決定是否除以1000。如果乘以過1000,表明后臺(tái)給你傳過來的是毫秒。?
?
轉(zhuǎn)載于:https://www.cnblogs.com/ios-wanglong/p/5136992.html
總結(jié)
- 上一篇: Monte carlo
- 下一篇: PHP 依赖注入,从此不再考虑加载顺序