iOS 日期总结:NSDate、NSDateFormatter

2018-10-24  本文已影响10人  恋空K

//(1)NSDate 初始化

// 初始化一个当前时刻对象

NSDate *now = [[NSDate alloc] init];

// 初始化一个明天当前时刻对象

NSDate *tomorrow = [[NSDate alloc] initWithTimeIntervalSinceNow:24*60*60];

// 初始化一个昨天当前时刻对象

NSDate *yesterday = [[NSDate alloc] initWithTimeInterval:-24*60*60 sinceDate:now];

// 初始化一个 2001-01-01 08:00:00 1小时后的时刻对象

NSDate *oneHourAfterReferenceDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:60*60];

// 初始化一个 1970-01-01 08:00:00 1小时后的时刻对象

NSDate *oneHourAfter1970 = [[NSDate alloc] initWithTimeIntervalSince1970:60*60];

//(2)获取日期描述

NSString *dateDescription = now.description;

//(3)获取时间间隔

// 获取今天到明天的时间间隔

NSTimeInterval interval1 = [tomorrow timeIntervalSinceDate:now];

// 获取今天到明天的时间间隔

NSTimeInterval interval2 = [tomorrow timeIntervalSinceNow];

// 获取 2001-01-01 08:00:00 到今天的时间间隔

NSTimeInterval interval3 = [now timeIntervalSinceReferenceDate];

// 获取 1970-01-01 08:00:00 到今天的时间间隔

NSTimeInterval interval4 = [now timeIntervalSince1970];

-//(4)随机返回一个不可能达到的未来时间、过去时间

NSDate *futureDate = [NSDate distantFuture];

NSDate *pastDate = [NSDate distantPast];

//(5)时间相加

// 返回一个后天当前时刻对象(在明天基础上再加上一天的时间)

NSDate *theDayAfterTomorrow = [tomorrow dateByAddingTimeInterval:24*60*60];

//(6)时间比较

// 比较两个时间对象是否相同返回布尔值(由于精度问题,isTheSameDate 为 false)

BOOL isTheSameDate = [theDayAfterTomorrow isEqualToDate:[[NSDate alloc] initWithTimeInterval:2*24*60*60 sinceDate:now]];

// 返回两个时间中较早的一个时间

NSDate *earlierOne = [now earlierDate:tomorrow];

// 返回两个时间中较晚的一个时间

NSDate *laterOne = [now laterDate:tomorrow];

// 比较两个时间对象是否相同并返回 NSComparisonResult 值

2、日期转换(NSDateFormatter)

//(1)方式1:用已有日期格式进行转换

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

dateFormatter.dateStyle = NSDateFormatterMediumStyle;

dateFormatter.timeStyle = NSDateFormatterMediumStyle;

NSDate *now = [[NSDate alloc] init];

// Date 转 String

NSString *nowString = [dateFormatter stringFromDate:now];

// String 转 Date

now = [dateFormatter dateFromString:nowString];

//(2)方式2:自定义日期格式进行转换

dateFormatter = [[NSDateFormatter alloc] init];

dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";

// Date 转 String

nowString = [dateFormatter stringFromDate:now];

// String 转 Date

now = [dateFormatter dateFromString:nowString];

来源:CSDN

原文:https://blog.csdn.net/jinnchang/article/details/4459280

上一篇 下一篇

猜你喜欢

热点阅读