Objective-C语法之NSCalendar的使用(包含NSDateComponents)

main.m

  1 #import <Foundation/Foundation.h>
  2 /**
  3  *  根据输入的时间,获取对应月份的天数
  4  *
  5  *  @param currentDate 输入的时间
  6  *
  7  *  @return 对应月份的天数
  8  */
  9 NSUInteger daysOfMonth(NSDate *currentDate) {
 10     NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
 11     NSRange range = [gregorian rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:currentDate];
 12     return range.length;
 13 }
 14 /**
 15  *  根据输入的时间,获取对应年份的天数
 16  *
 17  *  @param currentDate 输入的时间
 18  *
 19  *  @return 对应年份的天数
 20  */
 21 NSUInteger daysOfYear(NSDate *currentDate) {
 22     NSUInteger days = 0;
 23     NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
 24     NSDateComponents *comps = [gregorian components:NSCalendarUnitYear fromDate:currentDate];
 25
 26     for (NSUInteger i=1; i<=12; i++) {
 27         [comps setMonth:i];
 28         days += daysOfMonth([gregorian dateFromComponents:comps]);
 29     }
 30     return days;
 31 }
 32 /**
 33  *  根据输入的时间,获取对应月份的第一天时间
 34  *
 35  *  @param currentDate 输入的时间
 36  *
 37  *  @return 对应月份的第一天时间
 38  */
 39 NSDate* firstDayOfMonth(NSDate *currentDate) {
 40     NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
 41     unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
 42     NSDateComponents *comps = [gregorian components:unitFlags fromDate:currentDate];
 43     [comps setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; //使用UTC或GMT解决时区相差8小时的问题
 44     [comps setDay:1];
 45
 46     NSDate *firstDay = [gregorian dateFromComponents:comps];
 47     return firstDay;
 48 }
 49 /**
 50  *  根据输入的时间,获取对应月份的最后一天时间
 51  *
 52  *  @param currentDate 输入的时间
 53  *
 54  *  @return 对应月份的最后一天时间
 55  */
 56 NSDate* lastDayOfMonth(NSDate *currentDate) {
 57     NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
 58     unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
 59     NSDateComponents *comps = [gregorian components:unitFlags fromDate:currentDate];
 60     [comps setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; //使用UTC或GMT解决时区相差8小时的问题
 61     [comps setDay:daysOfMonth(currentDate)];
 62
 63     NSDate *lastDay = [gregorian dateFromComponents:comps];
 64     return lastDay;
 65 }
 66 /**
 67  *  根据输入的时间和添加的月数间隔、天数间隔,获取间隔后的时间
 68  *
 69  *  @param currentDate 输入的时间
 70  *  @param months      月数间隔
 71  *  @param days        天数间隔
 72  *
 73  *  @return 间隔后的时间
 74  */
 75 NSDate* addMonthAndDayToDate(NSDate *currentDate, NSUInteger months, NSUInteger days) {
 76     NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
 77     NSDateComponents *comps = [[NSDateComponents alloc] init];
 78     [comps setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; //使用UTC或GMT解决时区相差8小时的问题
 79     [comps setMonth:months];
 80     [comps setDay:days];
 81
 82     NSDate *newDate = [gregorian dateByAddingComponents:comps toDate:currentDate options:0];
 83     return newDate;
 84 }
 85 /**
 86  *  根据输入的开始时间和结束时间,获取间隔的时间数组(月数和天数;toDate-fromDate的比较值是有符号整数NSInteger,所以存在负数的可能)
 87  *
 88  *  @param fromDate 开始时间
 89  *  @param toDate   结束时间
 90  *
 91  *  @return 间隔的时间数组(月数和天数;toDate-fromDate的比较值是有符号整数NSInteger,所以存在负数的可能)
 92  */
 93 NSArray* monthAndDayBetweenTwoDates(NSDate *fromDate, NSDate *toDate) {
 94     NSMutableArray *mArrMonthAndDay = [[NSMutableArray alloc] initWithCapacity:2];
 95     NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
 96     unsigned unitFlags = NSCalendarUnitMonth |  NSCalendarUnitDay;
 97     NSDateComponents *comps = [gregorian components:unitFlags fromDate:fromDate toDate:toDate options:0];
 98
 99     [mArrMonthAndDay addObject:[NSString stringWithFormat:@"%ld", (long)[comps month]]];
100     [mArrMonthAndDay addObject:[NSString stringWithFormat:@"%ld", (long)[comps day]]];
101     return mArrMonthAndDay;
102 }
103 int main(int argc, const char * argv[]) {
104     @autoreleasepool {
105         NSDate *now = [NSDate date];
106         NSUInteger days = daysOfMonth(now);
107         NSLog(@"本月的天数=%lu", (unsigned long)days); //本月的天数=30
108
109         days = daysOfYear(now);
110         NSLog(@"本年的天数=%lu", (unsigned long)days); //本年的天数=365
111
112         NSDate *firstDay = firstDayOfMonth(now);
113         NSLog(@"firstDayOfMonth=%@", firstDay); //firstDayOfMonth=2015-04-01 00:58:39 +0000
114
115         NSDate *lastDay = lastDayOfMonth(now);
116         NSLog(@"lastDayOfMonth=%@", lastDay); //lastDayOfMonth=2015-04-30 00:58:39 +0000
117
118         NSDate *newDate = addMonthAndDayToDate(lastDay, 0, 2);
119         NSLog(@"lastDayOfMonth的后天=%@", newDate); //lastDayOfMonth的后天=2015-05-02 00:58:39 +0000
120
121         newDate = addMonthAndDayToDate(lastDay, 2, 2);
122         NSLog(@"lastDayOfMonth的2个月零2天后时间=%@", newDate); //lastDayOfMonth的2个月零2天后时间=2015-07-02 00:58:39 +0000
123
124         NSArray *arrMonthAndDay = monthAndDayBetweenTwoDates(firstDay, newDate);
125         NSLog(@"lastDayOfMonth的2个月零2天后时间和firstDayOfMonth相差(%@个月零%@天)", arrMonthAndDay[0], arrMonthAndDay[1]); //lastDayOfMonth的2个月零2天后时间和firstDayOfMonth相差(3个月零1天)
126     }
127     return 0;
128 }

结果:

1 2015-04-30 00:58:39.794 OCNSCalendar[988:83921] 本月的天数=30
2 2015-04-30 00:58:39.795 OCNSCalendar[988:83921] 本年的天数=365
3 2015-04-30 00:58:39.800 OCNSCalendar[988:83921] firstDayOfMonth=2015-04-01 00:58:39 +0000
4 2015-04-30 00:58:39.800 OCNSCalendar[988:83921] lastDayOfMonth=2015-04-30 00:58:39 +0000
5 2015-04-30 00:58:39.800 OCNSCalendar[988:83921] lastDayOfMonth的后天=2015-05-02 00:58:39 +0000
6 2015-04-30 00:58:39.800 OCNSCalendar[988:83921] lastDayOfMonth的2个月零2天后时间=2015-07-02 00:58:39 +0000
7 2015-04-30 00:58:39.800 OCNSCalendar[988:83921] lastDayOfMonth的2个月零2天后时间和firstDayOfMonth相差(3个月零1天)
时间: 2024-08-27 10:07:20

Objective-C语法之NSCalendar的使用(包含NSDateComponents)的相关文章

《黑马程序员》 NSArray和NSMutableArray的使用(Objective - c语法)

------- <a href="http://www.itheima.com" target="blank">Windows Phone 7手机开发</a>.<a href="http://www.itheima.com" target="blank">.Net培训</a>.期待与您交流! ------- 1 NSArray 的使用方法 • Foundation中数组(NSAr

初学Objective - C语法之代码块(block)

一.block声明 1.无参数,无返回值: void (^sayHi)(); 2.有参数,有返回值: NSInteger (^operateOfValue)(NSInteger num); block的声明:返回值类型(^block变量名)(参数列表) 脱字符(^)是块的语法标记 二.block实现 block变量名 = ^返回值类型(参数列表) 1.  sayHi = ^{ NSLog(@"你好"); }; 2. operateOfValue = ^ NSInteger (NSInt

iOS开发——语法篇OC篇&amp;高级语法精讲二

Objective高级语法精讲二 Objective-C是基于C语言加入了面向对象特性和消息转发机制的动态语言,这意味着它不仅需要一个编译器,还需要Runtime系统来动态创建类和对象,进行消息发送和转发.下面通过分析Apple开源的Runtime代码(我使用的版本是objc4-646.tar)来深入理解Objective-C的Runtime机制. Runtime数据结构 在Objective-C中,使用[receiver message]语法并不会马上执行receiver对象的message方

markdown语法集锦

参考:http://wowubuntu.com/markdown/#blockquote 1. 标题 # 一级标题 ## 二级标题 ### 三级标题 共六级标题 2. 列表 有序列表:1,2,3: 无序列表:在文字前加-或*. 子列表要求缩进,用空格或tab. 列表都是新的一行,符号要和文字之间加一个字符空格 3. 粗体 两个*包含一段文字就是粗体语法. 4. 斜体 一个*包含一段文本就是斜体语法. 5. 分割线 另起一行,连续输入三个*或三个-. 6. 代码框 两个`把中间代码包裹起来(支持t

jsp语法与jsp基本知识点

[jsp基本知识点] JSP全称是Java Server Pages,它和servlet技术一样,都是SUN公司定义的一种用于开发动态web资源的技术. JSP/Servlet规范. JSP实际上就是Servlet JSP这门技术的最大的特点在于,写jsp就像在写html,但它相比html而言,html只能为用户提供静态数据,而jsp技术允许在页面中嵌套java代码,为用户提供动态数据. [JSP模板元素] JSP页面中的HTML内容称之为JSP模板元素 JSP模板元素定义了网页的基本骨架,即定

Rust 1.7.0 语法基础 attribute

一.语法 attribute : '#' '!' ? '[' meta_item ']' ; meta_item : ident [ '=' literal | '(' meta_seq ')' ] ? ; meta_seq : meta_item [ ',' meta_seq ] ? ; 二.说明 使用Java的人都知道,Java有个 annotation 注解. Rust 也有注释,名称和C#的注释一样,叫做 attribute. Rust attribute 用于在源代码中标识编译过程中的

lua 5.1语法约定

Lua 5.1参考手册 由罗伯特·Ierusalimschy路易斯Henrique de Figueiredo沃尔德蔡氏 ?一个版权?2006 A¢A€"2012 Lua.org,银行业者.免费的根据Lua许可证. 内容一个?·指数一个?·其他版本一个?·英语一个?·portuguA?Aa年代一个?·espaA?A±ol 1 A¢A€"介绍 Lua是一个扩展编程语言设计的支持一般过程式编程与数据描述设施.它还提供了很好的支持面向对象编程,函数式编程,数据驱动的编程.Lua是打算作为一个

ASP.NET Razor——ASP.NET Razor - C#代码语法

Razor 同时支持 C# (C sharp) 和 VB (Visual Basic). 主要的 Razor C# 语法规则 Razor 代码块包含在 @{ ... } 中 内联表达式(变量和函数)以 @ 开头 代码语句用分号结束 变量使用 var 关键字声明 字符串用引号括起来 C# 代码区分大小写 C# 文件的扩展名是 .cshtml C# 实例 <!-- Single statement block -->@{ var myMessage = "Hello World"

摘录-IT企业必读的200个.NET面试题-03 .NET类型语法基础

基础类型和语法 Q: System.Object中包含哪些方法,哪些是虚方法 System.Object包含了Finalize在内的8个方法,其中有3个虚方法:Equals.GetHashCode和ToString方法. Q: 值类型和引用类型的区别 所有的值类型都继承自System.ValueType,常用的值类型包括结构.枚举.整数型.浮点型.布尔型等.值类型的赋值会产生一个新的数据副本,所以每个值类型都拥有一个数据副本,而引用类型的赋值则是赋值引用.值类型的对象分配在堆栈上,而引用类型的对