http://blog.csdn.net/lingedeng/article/details/6996599

Dates

NSDate类提供了创建date,比较date以及计算两个date之间间隔的功能。Date对象是不可改变的。

如果你要创建date对象并表示当前日期,你可以alloc一个NSDate对象并调用init初始化:

[cpp] view plaincopy
  1. NSDate *now = [[NSDate alloc] init];

或者使用NSDate的date类方法来创建一个日期对象。如果你需要与当前日期不同的日期,你可以使用NSDate的initWithTimeInterval...或dateWithTimeInterval...方法,你也可以使用更复杂的calendar或date components对象。

创建一定时间间隔的NSDate对象:

[plain] view plaincopy
  1. NSTimeInterval secondsPerDay = 24 * 60 * 60;
  2. NSDate *tomorrow = [[NSDate alloc] initWithTimeIntervalSinceNow:secondsPerDay];
  3. NSDate *yesterday = [[NSDate alloc] initWithTimeIntervalSinceNow:-secondsPerDay];
  4. [tomorrow release];
  5. [yesterday release];

使用增加时间间隔的方式来生成NSDate对象:

[plain] view plaincopy
  1. NSTimeInterval secondsPerDay = 24 * 60 * 60;
  2. NSDate *today = [[NSDate alloc] init];
  3. NSDate *tomorrow, *yesterday;
  4. tomorrow = [today dateByAddingTimeInterval: secondsPerDay];
  5. yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
  6. [today release];

如果要对NSDate对象进行比较,可以使用isEqualToDate:, compare:, laterDate:和 earlierDate:方法。这些方法都进行精确比较,也就是说这些方法会一直精确比较到NSDate对象中秒一级。例如,你可能比较两个日期,如果他们之间的间隔在一分钟之内则认为这两个日期是相等的。在这种情况下使用,timeIntervalSinceDate:方法来对两个日期进行比较。下面的代码进行了示例:

[plain] view plaincopy
  1. if (fabs([date2 timeIntervalSinceDate:date1]) < 60) ...

NSCalendar & NSDateComponents

日历对象封装了对系统日期的计算,包括这一年开始,总天数以及划分。你将使用日历对象对绝对日期与date components(包括年,月,日,时,分,秒)进行转换。

NSCalendar定义了不同的日历,包括佛教历,格里高利历等(这些都与系统提供的本地化设置相关)。NSCalendar与NSDateComponents对象紧密相关。

你可以通过NSCalendar对象的currentCalendar方法来获得当前系统用户设置的日历。

[plain] view plaincopy
  1. NSCalendar *currentCalendar = [NSCalendar currentCalendar];
  2. NSCalendar *japaneseCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSJapaneseCalendar];
  3. NSCalendar *usersCalendar = [[NSLocale currentLocale] objectForKey:NSLocaleCalendar];

usersCalendar和currentCalendar对象是相等的,尽管他们是不同的对象。

你可以使用NSDateComponents对象来表示一个日期对象的组件——例如年,月,日和小时。如果要使一个NSDateComponents对象有意义,你必须将其与一个日历对象相关联。下面的代码示例了如何创建一个NSDateComponents对象:

[plain] view plaincopy
  1. NSDateComponents *components = [[NSDateComponents alloc] init];
  2. [components setDay:6];
  3. [components setMonth:5];
  4. [components setYear:2004];
  5. NSInteger weekday = [components weekday]; // Undefined (== NSUndefinedDateComponent)

要将一个日期对象解析到相应的date components,你可以使用NSCalendar的components:fromDate:方法。此外日期本身,你需要指定NSDateComponents对象返回组件。

[plain] view plaincopy
  1. NSDate *today = [NSDate date];
  2. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  3. NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
  4. NSInteger day = [weekdayComponents day];
  5. NSInteger weekday = [weekdayComponents weekday];
  6. 同样你也可以从NSDateComponents对象来创建NSDate对象:
  7. NSDateComponents *components = [[NSDateComponents alloc] init];
  8. [components setWeekday:2]; // Monday
  9. [components setWeekdayOrdinal:1]; // The first Monday in the month
  10. [components setMonth:5]; // May
  11. [components setYear:2008];
  12. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  13. NSDate *date = [gregorian dateFromComponents:components];

为了保证正确的行为,您必须确保使用的组件在日历上是有意义的。指定“出界”日历组件,如一个-6或2月30日在公历中的日期值产生未定义的行为。

你也可以创建一个不带年份的NSDate对象,这样的操作系统会自动生成一个年份,但在后面的代码中不会使用其自动生成的年份。

[plain] view plaincopy
  1. NSDateComponents *components = [[NSDateComponents alloc] init];
  2. [components setMonth:11];
  3. [components setDay:7];
  4. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  5. NSDate *birthday = [gregorian dateFromComponents:components];

下面的示例显示了如何从一个日历置换到另一个日历:

[plain] view plaincopy
  1. NSDateComponents *comps = [[NSDateComponents alloc] init];
  2. [comps setDay:6];
  3. [comps setMonth:5];
  4. [comps setYear:2004];
  5. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  6. NSDate *date = [gregorian dateFromComponents:comps];
  7. [comps release];
  8. [gregorian release];
  9. NSCalendar *hebrew = [[NSCalendar alloc] initWithCalendarIdentifier:NSHebrewCalendar];
  10. NSUInteger unitFlags = NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;
  11. NSDateComponents *components = [hebrew components:unitFlags fromDate:date];
  12. NSInteger day = [components day]; // 15
  13. NSInteger month = [components month]; // 9
  14. NSInteger year = [components year]; // 5764

历法计算

在当前时间加上一个半小时:

[plain] view plaincopy
  1. NSDate *today = [[NSDate alloc] init];
  2. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  3. NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
  4. [offsetComponents setHour:1];
  5. [offsetComponents setMinute:30];
  6. // Calculate when, according to Tom Lehrer, World War III will end
  7. NSDate *endOfWorldWar3 = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];

获得当前星期中的星期天(使用格里高利历):

[plain] view plaincopy
  1. NSDate *today = [[NSDate alloc] init];
  2. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  3. // Get the weekday component of the current date
  4. NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];
  5. /*
  6. Create a date components to represent the number of days to subtract from the current date.
  7. The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question.  (If today is Sunday, subtract 0 days.)
  8. */
  9. NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
  10. [componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)];
  11. NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];
  12. /*
  13. Optional step:
  14. beginningOfWeek now has the same hour, minute, and second as the original date (today).
  15. To normalize to midnight, extract the year, month, and day components and create a new date from those components.
  16. */
  17. NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: beginningOfWeek];
  18. beginningOfWeek = [gregorian dateFromComponents:components];

如何可以计算出一周的第一天(根据系统的日历设置):

[cpp] view plaincopy
  1. NSDate *today = [[NSDate alloc] init];
  2. NSDate *beginningOfWeek = nil;
  3. BOOL ok = [gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:NULL forDate: today];

获得两个日期之间的间隔:

[cpp] view plaincopy
  1. NSDate *startDate = ...;
  2. NSDate *endDate = ...;
  3. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  4. NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
  5. NSDateComponents *components = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
  6. NSInteger months = [components month];
  7. NSInteger days = [components day];

使用Category来计算同一时代(AD|BC)两个日期午夜之间的天数:

[plain] view plaincopy
  1. @implementation NSCalendar (MySpecialCalculations)
  2. -(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate {
  3. NSInteger startDay=[self ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:startDate];
  4. NSInteger endDay=[self ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:endDate];
  5. return endDay-startDay;
  6. }
  7. @end

使用Category来计算不同时代(AD|BC)两个日期的天数:

[plain] view plaincopy
  1. @implementation NSCalendar (MyOtherMethod)
  2. -(NSInteger) daysFromDate:(NSDate *) startDate toDate:(NSDate *) endDate {
  3. NSCalendarUnit units=NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
  4. NSDateComponents *comp1=[self components:units fromDate:startDate];
  5. NSDateComponents *comp2=[self components:units fromDate endDate];
  6. [comp1 setHour:12];
  7. [comp2 setHour:12];
  8. NSDate *date1=[self dateFromComponents: comp1];
  9. NSDate *date2=[self dateFromComponents: comp2];
  10. return [[self components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0] day];
  11. }
  12. @end

判断一个日期是否在当前一周内(使用格里高利历):

[plain] view plaincopy
  1. -(BOOL)isDateThisWeek:(NSDate *)date {
  2. NSDate *start;
  3. NSTimeInterval extends;
  4. NSCalendar *cal=[NSCalendar autoupdatingCurrentCalendar];
  5. NSDate *today=[NSDate date];
  6. BOOL success= [cal rangeOfUnit:NSWeekCalendarUnit startDate:&start interval: &extends forDate:today];
  7. if(!success)
  8. return NO;
  9. NSTimeInterval dateInSecs = [date timeIntervalSinceReferenceDate];
  10. NSTimeInterval dayStartInSecs= [start timeIntervalSinceReferenceDate];
  11. if(dateInSecs > dayStartInSecs && dateInSecs < (dayStartInSecs+extends)){
  12. return YES;
  13. }
  14. else {
  15. return NO;
  16. }
  17. }

转载于:https://www.cnblogs.com/geek6/p/4092794.html

iphone——日期处理相关推荐

  1. android仿iphone日期时间选择器,Android仿iPhone日期时间选择器详解

    本文实例为大家分享了Android仿iPhone时间选择器的具体代码,供大家参考,具体内容如下 先看效果图 如何使用 import java.text.DateFormat; import java. ...

  2. JavaScriptTXT

    资源 | 10套好用的前端框架.设计组件库推荐 https://www.ui.cn/detail/332889.html 发现苹果手机alert出来的毫秒数,始终是NAN https://www.ji ...

  3. iPhone 5的发布日期估计为9月21日挂

    l国外有媒体披露了iPhone 5的发布日期,估计是在9月21日.如果这消息属实,这可能意味着苹果将宣布在未来的iPhone早在9月iPhone发布日期通常几天后宣布发生. 这不是第一次,我们听到了, ...

  4. iphone 如何获得系统时间和日期

    iphone 如何获得系统时间和日期 代码如下: #import <time.h> 1.获得当前的系统时间和日期 //获得系统时间 NSDate * senddate=[NSDate da ...

  5. 苹果保修期查询_查询iPhone的保修日期和激活日期

    当我们入手了一台新的iPhone,怕是二手或者是翻新机.你就需要去查询设备的保修日期了,来判断是否有无激活使用过.那么又该如何操作呢? 在手机设置查看 前往手机的[设置]-[通用]-[关于本机] 在[ ...

  6. element 日期选择图标_更换 App 图标,自制透明小组件!这可能是最全的 iPhone 桌面美化指南...

    说到个性化手机,你会想到换主题.换图标这些方法,不论是小清新还是偶像派,喜欢什么你就换什么.可如果你是 iPhone 用户,除了更换壁纸,也就能想想修改 app 文件夹名称了.Android 手机拥有 ...

  7. iPhone 13 发布日期、规格、预期价格等信息超全汇总

    iPhone 13 的发布指日可待,关于iPhone13你都有哪些想要了解的呢?macw为大家带来各种信息汇总,iPhone13发布日期.规格.价格等,你想了解的这儿都有! iPhone 13 发布日 ...

  8. 查看iphone手机产地/日期/是否国产

    一.iPhone产地 全球的iPhone手机基本上都来自中国大陆富士康生产,而富士康在大陆的工厂很多,不过负责生产iPhone手机主要在深圳.成都以及郑州三个城市. iPhone手机的序列号第1位英文 ...

  9. iphone日历怎么跳转日期_晚上别调手表日期!手表调节日历的禁区!

    最近,我们经常收到一些表友的提问,他们表示,在给腕表调时间的时候,手表总是调着调着就不走了,这是为什么呢? 日历手表的禁区问题由来已久,在晚上某个特定时间调日历,有可能损坏手表的日历功能,名修手表维修 ...

最新文章

  1. ‘%.2f‘ 与 ‘{:.2f}‘.format(w) 区别
  2. 学校拥有计算机清单和所放位置说明,大学计算机基础期末考试指南(2011)
  3. linux系统搭建ftp服务器--只给某个用户访问其默认目录下的文件
  4. C#编写TensorFlow人工智能应用 TensorFlowSharp
  5. Visual Studio 20xx试用版升级为正式版(WIN7同样有效)图解、附带序列号
  6. 8年测试经验,用例设计竟然不知道状态图法?
  7. closewin关闭无法返回上一层_紧急关闭iOS13,有史以来跳版本关闭系统
  8. 【机器学习】监督学习--(回归)岭回归
  9. Modelsim的下载及安装
  10. VMware 15.6版本下载安装
  11. Sm4【国密4加密解密】实战
  12. 一分钟了解“Matlab画三维空间中的点plot3”
  13. 求123456789=x成立个数
  14. uabntu镜像文件的后缀
  15. 数据管理平台系列之Zeppline安装与使用
  16. 透明与不透明物体共存
  17. 5OSPF的邻居和NBMA环境下的邻居
  18. 简单的nodejs+socket.io给指定的人发送消息
  19. 一千零一夜的观后感(一)
  20. Linux命令查询服务器名称和型号

热门文章

  1. redis创建像mysql表结构_如何给redis添加新数据结构
  2. Python的操作符重载
  3. Robust principal component analysis?(RPCA简单理解)
  4. 全球及中国清洁能源发电行业需求容量及应用前景分析报告2021-2027年
  5. 如何将表中的数据导出到电子表格中
  6. python学习(1)
  7. oracle 11g 数据库恢复技术 ---03 补充日志
  8. Pandas CookBook -- 02DataFrame基础操作
  9. Spring事务管理器分类
  10. 没有连接上aspnetdb.mdf数据库