獲取系統(tǒng)時間
#import <Foundation/Foundation.h>
void printDate(NSDate * date) {
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy年MM月dd日 HH時mm分ss秒"];
//默認(rèn)輸出 以零時區(qū)為基準(zhǔn)
NSLog(@"%@", date);
//計算機(jī)設(shè)置時區(qū)為基準(zhǔn)
NSLog(@"%@",[dateFormatter stringFromDate:date]);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
//獲取當(dāng)前時間
NSDate *date = [[NSDate alloc] init];
printDate(date);
//initWithTimeIntervalSinceNow 從當(dāng)前時間偏移 單位:秒
date = [[NSDate alloc] initWithTimeIntervalSinceNow:60];
printDate(date);
//initWithTimeIntervalSince1970 從1970-01-01 00:00:00偏移 單位:秒
date = [[NSDate alloc] initWithTimeIntervalSince1970:60*60*4];
printDate(date);
}
return 0;
}
?時間的比較
#import <Foundation/Foundation.h>
void printDate(NSDate * date) {
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy年MM月dd日 HH時mm分ss秒"];
//計算機(jī)設(shè)置時區(qū)為基準(zhǔn)
NSLog(@"%@",[dateFormatter stringFromDate:date]);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
//獲取當(dāng)前時間
NSDate *dateNew = [[NSDate alloc] init];
printDate(dateNew);
NSDate *dateOld = [[NSDate alloc] initWithTimeIntervalSinceNow:-60];
printDate(dateOld);
NSDate *dateFuture = [[NSDate alloc] initWithTimeIntervalSinceNow:60];
printDate(dateFuture);
//一個時間與另一個時間比較
double x1 = [dateNew timeIntervalSinceDate:dateOld];
//一個時間與當(dāng)前時間比較
double x2 = [dateFuture timeIntervalSinceNow];
printf("%lf\n%lf\n",x1,x2);
}
return 0;
}
自定義時間格式
NSDate *date = [[NSDate alloc]init];NSDateFormatter *dateFormatter1 = [NSDateFormatter new];NSDateFormatter *dateFormatter2 = [NSDateFormatter new];NSDateFormatter *dateFormatter3 = [NSDateFormatter new];NSDateFormatter *dateFormatter4 = [NSDateFormatter new];[dateFormatter1 setDateFormat:@"yyyy年MM月dd日 HH時mm分ss秒"];[dateFormatter2 setDateFormat:@"MM月dd日 HH時mm"];[dateFormatter3 setDateFormat:@"yyyy年MM月dd日"];[dateFormatter4 setDateFormat:@"HH時mm分ss秒"];NSLog(@"%@",[dateFormatter1 stringFromDate:date]);NSLog(@"%@",[dateFormatter2 stringFromDate:date]);NSLog(@"%@",[dateFormatter3 stringFromDate:date]);NSLog(@"%@",[dateFormatter4 stringFromDate:date]);
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者