获取系统时间
#import <Foundation/Foundation.h>
void printDate(NSDate * date) {
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
//默认输出 以零时区为基准
NSLog(@"%@", date);
//计算机设置时区为基准
NSLog(@"%@",[dateFormatter stringFromDate:date]);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
//获取当前时间
NSDate *date = [[NSDate alloc] init];
printDate(date);
//initWithTimeIntervalSinceNow 从当前时间偏移 单位:秒
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秒"];
//计算机设置时区为基准
NSLog(@"%@",[dateFormatter stringFromDate:date]);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
//获取当前时间
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];
//一个时间与当前时间比较
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]);