iOS 日期总结:NSDate、NSDateFormatter

//(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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • ——那石藏于寂寂林中,如玉之美,如冰之洁,有珺的诱惑,诱惑渴求放任无言的短暂欣欢 美,动人心魄,魂牵梦绕 感受美,...
    一二山放肆阅读 1,463评论 0 0
  • 很多时候,别人施加给自己压力,委屈,会让你喘不过来气。内心有种种的不平衡,太委屈以很多种方式发泄。然后你开始努力,...
    潇潇潇涵儿阅读 4,114评论 0 0
  • 時隔結業2年的時間,高五期再度相聚,甚似開心。 早上雖然出門各種堵,但是當到達目的地時,大家很興奮。中午的柴火雞,...
    好彩妹阅读 2,361评论 0 0
  • 区块链1.0是指以共识证明、加密算法和数字签名为核心的系统(以比特币为代表,应用于货币体系),2.0是指在1.0基...
    lichald阅读 5,167评论 0 51

友情链接更多精彩内容