NSDate对象用来表示一个具体的时间点,它存储的是世界标准时间,所以在使用的时候可能会需要根据不同的时区将时间转换为本地时间。
时间转换:默认情况下,通过NSDate获取的日期时间格式为:yyyy-MM-dd HH:mm:ss
// NSDateFormatter类对日期格式进行转换,在使用NSDateFormatter类进行日期转换之前,需要设置日期的格式。
/* 格式化设置
y 年
M 月
d 日
H / h 时 (24小时制/12小时制)
m 分
s 秒
*/
// NSDate类中提供了date方法,用来获取当前标准时区的时间。
NSDate *date = [NSDate date];
NSLog(@"国际标准时间: %@",date);
// 获取系统当前时区
NSTimeZone *zone = [NSTimeZone systemTimeZone];
// 获取当前时区与格林尼治时间的间隔
NSInteger interval = [zone secondsFromGMTForDate:date];
// 获取本地时间
NSDate *localDate = [NSDate dateWithTimeIntervalSinceNow:interval];
NSLog(@"本地时间: %@",localDate);
-(NSString *)stringFromDate:(NSDate *)date; // NSDate转NSString
-(nullable NSDate *)dataFromString:(NSString *)string; // NSString转NSDate
// 日期格式转换
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = @"yyyy年MM月dd日 HH:mm:ss";
NSString date2String = [df stringFromDate:date];
NSLog(@"日期转换字符串: %@",date2String );
NSDate string2Date = [df dateFromString:date2String];
NSLog(@"字符串转换日期: %@",string2Date );
// 比较两个时间对象的先后,可以使用earlierDate以及laterDate方法。
-(NSDate *)earlierDate:(NSDate *)anotherDate;
-(NSDate *)laterDate:(NSDate *)anotherDate;
// 比较两个时间的间隔,可以使用timeIntervalSinceDate:方法。
-(NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate;
// 比较两个日期是否相等,可以使用isEqualToDate:方法。
-(BOOL)isEqualToDate:(NSDate *)otherDate;
NSDate *date1 = [NSDate date];
NSDate *date2 = [NSDate dateWithTimeIntervalSinceNow: 10];
NSDate *tempDate = [[NSDate alloc] init];
tempDate = [date1 earlierDate:date2];
// 比较两个时间的间隔
NSTimeInterval tInterval = [date2 timeIntervalSinceDate:date1];