【iOS开发】值对象篇----日期相关

1.【NSDate----日期】</span>
 	//返回当前日期 以格林尼治为准 GMT+8
        NSDate *date1 = [NSDate date];
        
        //返回以当前日期为准3600秒之后的时间
        NSDate * date2 = [NSDate dateWithTimeIntervalSinceNow:10];
        
        //将定时器(NSTimer)的启动时间,设为很多年前的一天,可以唤醒定时器;将定时器的启动时间,设为未来一天,可以休眠定时器。
        //未来的时间
        NSDate * date3 = [NSDate distantFuture];
        //过去的时间
        NSDate * date4 = [NSDate distantPast];
        
        //返回1970.1.1.0时之后3600秒的时间
        NSDate * dateSince1970 = [NSDate dateWithTimeIntervalSince1970:3600];
<span style="white-space:pre">	</span>
        //返回date1距离现在多少秒
        NSTimeInterval secs = [date1 timeIntervalSinceNow];
        NSLog(@"%.0f", secs);
<span style="white-space:pre">	</span>//定时器,定时5s
        //首先获得5s之后的时间
         NSDate * endDate = [NSDate dateWithTimeIntervalSinceNow:5];
         //每一秒获得一次当前时间
         while ([[NSDate date] timeIntervalSinceReferenceDate] < endDate.timeIntervalSinceReferenceDate) {
         sleep(1);
         }

2.【NSTimeZone -- 时区信息

-(void)testNSTimeZone
{
    /*初始化方法
    */
    //1.根据时区名称初始化
    NSTimeZone * timeZone1 = [[NSTimeZone alloc]initWithName:@"America/Chicago"];
    //2.根据时区缩写来初始化 如EST(美国东部标准时间 )HKT 香港标准时间
    NSTimeZone *timeZone2 = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
    //3.返回系统时区
    NSTimeZone * timeZone3 = [NSTimeZone systemTimeZone];
    
    //4.返回本地时区 与系统时区区别在于本地市区可以修改 系统时区不可修改
    NSTimeZone * timeZone4 = [NSTimeZone localTimeZone];
    
    //5.根据零时区的秒数便宜返回一个新时区对象
    NSTimeZone * timeZone5 = [NSTimeZone timeZoneForSecondsFromGMT:28800];
    NSLog(@"%@",timeZone5);
    
    //常用API
    //1.以数组形式返回所有已知的时区名称
    NSArray * arr = [NSTimeZone knownTimeZoneNames];
    for (NSString * str  in arr) {
        NSLog(@"%@",str);
    }
    //2.返回时区对象的名称或缩写
    NSTimeZone * local = [NSTimeZone localTimeZone];
    NSString * strZoneName = [local name];
    NSString * strZoneAbbreviation = [local abbreviation];
    NSLog(@"%@",strZoneName);
    NSLog(@"%@",strZoneAbbreviation);
    
    //3.得到当前时区与零时区的间隔秒数
    NSTimeZone *zone = [NSTimeZone localTimeZone];
    int secs =(int) [zone secondsFromGMT];
    NSLog(@"%d",secs);
}

3.【 NSLoale类返回本地化信息,主要体现在"语言"和"区域格式"这两个设置项。

-(void)testNSLocal
{
    /*初始化*/
    //1.返回系统本地化信息
    NSLocale * locale = [NSLocale systemLocale];
    NSLog(@"%@",[[locale objectForKey:NSLocaleCalendar] calendarIdentifier]);
    //2.+ (id)currentLocale / + (id)autoupdatingCurrentLocale
    /*
    这两个类方法都将返回当前客户端的本地化信息,区别在于:currentLocale取得的值会一直保持在cache中,第一次用此方法实例化对象后,即使修改了本地化设定,这个对象也不会改变。而使用autoupdatingCurrentLocale,当每次修改本地化设定,其实例化的对象也会随之改变。
     */
    NSLocale * locale1 = [NSLocale currentLocale];
    NSLocale *locale2 = [NSLocale autoupdatingCurrentLocale];
    NSLog(@"%@",locale1.localeIdentifier);
    NSLog(@"%@",locale2.localeIdentifier);
    
    //3.用标识符初始化本地化信息
    //代码用"zh_CN"来初始化对象,然后再打印出对象的货币符号,得到的结果是人民币符号¥
    NSLocale *locale3 = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
    NSString * strS = [locale3 objectForKey:NSLocaleCurrencySymbol];
    NSLog(@"%@",strS);
    //常用对象方法与类方法
    //1.根据不同的key返回各种本地化信息,例如下面的代码返回了当前货币符号:
    NSLocale *locale4 = [NSLocale currentLocale];
    NSString *strSymbol = [locale4 objectForKey:NSLocaleCurrencySymbol];
    NSCalendar *calendar = [[NSLocale currentLocale] objectForKey:NSLocaleCalendar];
    //2.显示特定地区代号下相应键的显示名称:
    //第一句代码代表以中文来实例化对象,然后得到"en_US"的NSLocaleIdentifier键的显示名称。最后输出的结果是"英文(美国)"
    NSLocale * locale5 = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
    NSString * str = [locale5 displayNameForKey:NSLocaleIdentifier value:@"en_US"];
    NSLog(@"%@",str);
}

4.【NSDateComponents】日期组件 封装了具体年月日 时分秒 周 季度等信息。

-(void)testNSDateCompoments
{
    //1.初始化
    NSDateComponents * compt = [[NSDateComponents alloc]init];
    [compt setEra:1];
    [compt setYear:2013];
    [compt setMonth:3];
    [compt setDay:15];
    [compt setHour:11];
    [compt setMinute:20];
    [compt setSecond:55];
    [compt setQuarter:2];
    [compt setTimeZone:[NSTimeZone systemTimeZone]];
    [compt setWeek:3];
    [compt setWeekday:4];
    [compt setWeekOfMonth:3];
    [compt setWeekOfYear:2];
    [compt setCalendar:[NSCalendar currentCalendar]];
    //相关方法
    //1.取得一个NSDate对象的1个或多个部分 用 NSDateComponets封装
    NSCalendar * calendar = [NSCalendar currentCalendar];
    NSDate *date = [NSDate date];
    
    NSDateComponents * compt2 = [calendar components:(NSYearCalendarUnit|
                                                      NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:date];
    NSLog(@"%ld,%@",[compt2 year],date);
    NSLog(@"%ld,%@",[compt2 month],date);
    NSLog(@"%ld.%@",[compt2 day],date);
    
    //2.NSDate中方法
    // - (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options : (NSUInteger)opts
    //取得两个NSDate对象的间隔 用NSDateComponents封装
    NSCalendar * cal = [NSCalendar currentCalendar];
    NSDate *d1 = [NSDate date];
    NSDate * d2 = [NSDate dateWithTimeInterval:5+100 sinceDate:d1];
    NSDateComponents *com = [calendar components:(NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate: d2 toDate:d1 options:0];
    NSLog(@"%ld",[com minute]);
    NSLog(@"%ld",[com second]);
    
    
    //- (NSDate *)dateFromComponents:(NSDateComponents *)comps
    //根据一个NSDateComponents对象得到一个NSDate对象
    NSDateComponents * com2 = [[NSDateComponents alloc]init];
    [com2 setYear:2012];
    [com2 setMonth:4];
    [com2 setDay:11];
    NSCalendar * calendar2 = [NSCalendar currentCalendar];
    NSDate *d3 = [calendar2 dateFromComponents:com2];
    
    NSLog(@"%@",d3);
    //得到本地时间 避免时区问题
    NSTimeZone * zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:d3];
    
    NSDate * localeDate = [d3 dateByAddingTimeInterval:interval];
    
    //NSCalendar对象的 - (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSUInteger)opts
    
    //在参数date基础上,增加一个NSDateComponents类型的时间增量
    NSDateComponents *compt3 = [[NSDateComponents alloc] init];
    [compt3 setDay:25];
    [compt3 setHour:4];
    [compt3 setMinute:66];
    //
    NSCalendar * calendar4= [NSCalendar currentCalendar];
    NSDate * date4 = [calendar dateByAddingComponents:compt3 toDate:[NSDate date] options:0];
    
    //时区问题
    NSTimeZone *zone4 = [NSTimeZone systemTimeZone];
    NSInteger interval4 = [zone secondsFromGMTForDate:date4];
    NSDate *localeDate4 = [date dateByAddingTimeInterval:interval4];
    NSLog(@"%@",localeDate4);
}

【NSCalendar】

NSCalendar

1. + (id)currentCalendar / + (id)autoupdatingCurrentCalendar

这两个类方法都将返回当前客户端的逻辑日历,区别在于:currentCalendar取得的值会一直保持在cache中,第一次用此方法实例化对象后,即使修改了系统日历设定,这个对象也不会改变。而使用autoupdatingCurrentCalendar,当每次修改系统日历设定,其实例化的对象也会随之改变。

下面的代码演示了区别所在,假设初始Calendar设定为NSGregorianCalendar(公历),先用这两个函数分别初始化两个对象,然后修改系统日历为NSJapaneseCalendar(日本和历),再重新打印这两个对象的信息:


NSCalendar *calendar;
NSCalendar *calendar2;

- (IBAction)doTest:(id)sender 
{
    calendar = [NSCalendar currentCalendar];
    calendar2 = [NSCalendar autoupdatingCurrentCalendar];
    
    NSLog(@"%@",calendar.calendarIdentifier); //print "gregorian"
    NSLog(@"%@",calendar2.calendarIdentifier); //print "gregorian"
}

- (IBAction)doAgain:(id)sender 
{
    NSLog(@"%@",calendar.calendarIdentifier); //print "gregorian"
    NSLog(@"%@",calendar2.calendarIdentifier); //print "japanese"
}

2. - (id)initWithCalendarIdentifier:(NSString *)string

根据提供的日历标示符初始化

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSChineseCalendar];
NSLog(@"%@",calendar.calendarIdentifier);

系统中定义的日历有:

NSGregorianCalendar -- 公历
NSBuddhistCalendar -- 佛教日历
NSChineseCalendar -- 中国农历
NSHebrewCalendar -- 希伯来日历
NSIslamicCalendar -- 伊斯兰历
NSIslamicCivilCalendar -- 伊斯兰教日历
NSJapaneseCalendar -- 日本日历
NSRepublicOfChinaCalendar -- 中华民国日历(台湾)
NSPersianCalendar -- 波斯历
NSIndianCalendar -- 印度日历
NSISO8601Calendar -- ISO8601

NSCalendar常用对象方法与类方法:

1. - (void)setLocale:(NSLocale *)locale

设置本地化信息

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
NSLog(@"%@",calendar.locale.localeIdentifier);

2. - (void)setTimeZone:(NSTimeZone *)tz

设置时区信息

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"HKT"]];
NSLog(@"%@",calendar.timeZone);

3. - (void)setFirstWeekday:(NSUInteger)weekday

设置每周的第一天从星期几开始,比如:1代表星期日开始,2代表星期一开始,以此类推。默认值是1

如图所示,如果从星期天开始,日历的表现形式:

 

如果从星期二开始,日历的表现形式:

NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setFirstWeekday:3];
NSLog(@"%i",calendar.firstWeekday);

4. - (void)setMinimumDaysInFirstWeek:(NSUInteger)mdw

设置每年及每月第一周必须包含的最少天数,比如:设定第一周最少包括3天,则value传入3

NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setMinimumDaysInFirstWeek:3];
NSLog(@"%i",calendar.minimumDaysInFirstWeek);

5. - (NSUInteger)ordinalityOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date

获取一个小的单位在一个大的单位里面的序数

NSCalendarUnit包含的值有:

NSEraCalendarUnit -- 纪元单位。对于NSGregorianCalendar(公历)来说,只有公元前(BC)和公元(AD);而对于其它历法可能有很多,例如日本和历是以每一代君王统治来做计算。
NSYearCalendarUnit -- 年单位。值很大,相当于经历了多少年,未来多少年。
NSMonthCalendarUnit -- 月单位。范围为1-12
NSDayCalendarUnit -- 天单位。范围为1-31
NSHourCalendarUnit -- 小时单位。范围为0-24
NSMinuteCalendarUnit -- 分钟单位。范围为0-60
NSSecondCalendarUnit -- 秒单位。范围为0-60
NSWeekCalendarUnit -- 周单位。范围为1-53
NSWeekdayCalendarUnit -- 星期单位,每周的7天。范围为1-7
NSWeekdayOrdinalCalendarUnit -- 没完全搞清楚
NSQuarterCalendarUnit -- 几刻钟,也就是15分钟。范围为1-4
NSWeekOfMonthCalendarUnit -- 月包含的周数。最多为6个周
NSWeekOfYearCalendarUnit -- 年包含的周数。最多为53个周
NSYearForWeekOfYearCalendarUnit -- 没完全搞清楚
NSTimeZoneCalendarUnit -- 没完全搞清楚

下面是一些示例:

① 当小单位为NSWeekdayCalendarUnit,大单位为NSWeekCalendarUnit时(即某个日期在这一周是第几天),根据firstWeekday属性不同,返回的结果也不同。

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:10];   
//[calendar setFirstWeekday:2];
int count = [calendar ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:date];
NSLog(@"%d",count);

默认firstWeekday为1(星期天开始)的情况下,得到的结果是2,从下图可以看到是第2天。

假如firstWeekday被设置为2(星期一开始)的情况下,得到的结果是1,从下图可以看到是第1天

② 当小单位为NSWeekCalendarUnit,大单位为NSYearCalendarUnit时(即某个日期在这一年中是第几周),根据minimumDaysInFirstWeek属性不同,返回的结果也不同。


NSDateComponents *compt = [[NSDateComponents alloc] init];
[compt setYear:2013];
[compt setMonth:1];
[compt setDay:20];

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDate *date = [calendar dateFromComponents:compt];

//[calendar setMinimumDaysInFirstWeek:6];
int count = [calendar ordinalityOfUnit:NSWeekCalendarUnit inUnit:NSYearCalendarUnit forDate:date];
NSLog(@"%d",count);

从上图的日历中可以看出,在没有设置minimumDaysInFirstWeek的情况下,1月20日得到的结果是4(第四个周)。

默认情况下第一个周有5天,如果将minimumDaysInFirstWeek设置为6天,则原本是第一周的1月1日--1月5日被划分到了上一年,返回0;而1月6日--1月12日升为第一周,1月13日--1月19日升为第二周。。依此类推。

所以需要关注的是minimumDaysInFirstWeek与实际第一周包含天数的大小比较,如果提供的minimumDaysInFirstWeek比实际第一周的天数小,则一切不变;否则统计"一年中第几周"、"一个月中第几周"会产生变化。

6. - (NSRange)rangeOfUnit:(NSCalendarUnit)smaller inUnit:(NSCalendarUnit)larger forDate:(NSDate *)date

根据参数提供的时间点,得到一个小的单位在一个大的单位里面的取值范围


NSDateComponents *compt = [[NSDateComponents alloc] init];
[compt setYear:2013];
[compt setMonth:2];
[compt setDay:21];
[compt setHour:9];
[compt setMinute:45];
[compt setSecond:30];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [calendar dateFromComponents:compt];

//得到本地时间,避免时区问题
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:date];
NSDate *localeDate = [date dateByAddingTimeInterval:interval];

NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:localeDate];

NSLog(@"%d -- %d",range.location,range.length);

调用这个方法要明确一点,取得的是"范围"而不是"包含",下面是一些例子:

① 小单位是NSDayCalendarUnit,大单位是NSYearCalendarUnit,并不是要取这一年包含多少天,而是要取"天"(Day)这个单位在这一年(Year)的取值范围。其实不管你提供的日期是多少,返回的值都是"1--31"。

② 小单位是NSDayCalendarUnit,大单位是NSMonthCalendarUnit。要取得参数时间点所对应的月份下,"天"(Day)的取值范围。根据参数时间的月份不同,值也不同。例如2月是1--28、3月是1--31、4月是1--30。

③ 小单位是NSWeekCalendarUnit,大单位是NSMonthCalendarUnit。要取得参数时间点所对应的月份下,"周"(Week)的取值范围。需要注意的是结果会受到minimumDaysInFirstWeek属性的影响。在默认minimumDaysInFirstWeek情况下,取得的范围值一般是"1--5",从日历上可以看出来这个月包含5排,即5个周。

④ 小单位是NSDayCalendarUnit,大单位是NSWeekCalendarUnit。要取得周所包含的"天"(Day)的取值范围。下面是一个示例日历图:

在上图的日期条件下,假如提供的参数是4月1日--4月6日,那么对应的week就是1(第一个周),可以看到第一个周包含有6天,从1号开始,那么最终得到的范围值为1--6。

假如提供的参数是4月18日,那么对应的week是3(第三个周),第三个周包含有7天,从14号开始,那么最终得到的范围值是14--7。

假如提供的参数是4月30日,那么对应的week是5(第五个周),第五个周只包含3天,从28号开始,那么最终得到的范围值是28--3。

7. - (BOOL)rangeOfUnit:(NSCalendarUnit)unit startDate:(NSDate **)datep interval:(NSTimeInterval *)tip forDate:(NSDate *)date

根据参数提供的时间点,返回所在日历单位的开始时间。如果startDate和interval均可以计算,则返回YES;否则返回NO

unit -- 日历单位
datep -- 开始时间,通过参数返回
tip -- 日历单位所对应的秒数,通过参数返回
date -- 时间点参数


NSDate *dateOut = nil;
NSTimeInterval count = 0;

NSDateComponents *compt = [[NSDateComponents alloc] init];
[compt setYear:2013];
[compt setMonth:3];
[compt setDay:22];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [calendar dateFromComponents:compt];
BOOL b = [calendar rangeOfUnit:NSMonthCalendarUnit startDate:&dateOut interval:&count forDate:date];
if(b)
{
    //得到本地时间,避免时区问题
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:dateOut];
    NSDate *localeDate = [dateOut dateByAddingTimeInterval:interval];
    
    NSLog(@"%@",localeDate);
    NSLog(@"%f",count);
}
else
{
    NSLog(@"无法计算");
}

上面的例子要求返回2013年3月22日当月的起始时间,以及当月的秒数。得到的结果是:2013-03-01 00:00:00 +0000,2678400。(2678400 = 31天 * 24小时 * 60分 * 60秒)。

假如将上面的日历单位改为NSWeekCalendarUnit,那么得到的结果是:2013-03-17 00:00:00 +0000,604800。当周的第一天是3月17日。(604800 = 7天 * 24小时 * 60分 * 60秒)。

假如将上面的日历单位改为NSYearCalendarUnit,那么得到的结果是:2013-01-01 00:00:00 +0000,31536000。这一年的第一天是1月1日,(31536000 = 365天 * 24小时 * 60分 * 60秒)。

NSDateFormatter

NSDateFormatter的日期格式如下:

G -- 纪元
一般会显示公元前(BC)和公元(AD)

y -- 年
假如是2013年,那么yyyy=2013,yy=13  

M -- 月
假如是3月,那么M=3,MM=03,MMM=Mar,MMMM=March
假如是11月,那么M=11,MM=11,MMM=Nov,MMMM=November

w -- 年包含的周
假如是1月8日,那么w=2(这一年的第二个周)

W -- 月份包含的周(与日历排列有关)
假如是2013年4月21日,那么W=4(这个月的第四个周)

F -- 月份包含的周(与日历排列无关)
和上面的W不一样,F只是单纯以7天为一个单位来统计周,例如7号一定是第一个周,15号一定是第三个周,与日历排列无关。

D -- 年包含的天数
假如是1月20日,那么D=20(这一年的第20天)
假如是2月25日,那么D=31+25=56(这一年的第56天)

d -- 月份包含的天数
假如是5号,那么d=5,dd=05
假如是15号,那么d=15,dd=15

E -- 星期 
假如是星期五,那么E=Fri,EEEE=Friday

a -- 上午(AM)/下午(PM)

H -- 24小时制,显示为0--23
假如是午夜00:40,那么H=0:40,HH=00:40

h -- 12小时制,显示为1--12
假如是午夜00:40,那么h=12:40

K -- 12小时制,显示为0--11
假如是午夜00:40,那么K=0:40,KK=00:40

k -- 24小时制,显示为1--24
假如是午夜00:40,那么k=24:40

m -- 分钟
假如是5分钟,那么m=5,mm=05
假如是45分钟,那么m=45,mm=45

s -- 秒
假如是5秒钟,那么s=5,ss=05
假如是45秒钟,那么s=45,ss=45

S -- 毫秒
一般用SSS来显示

z -- 时区
表现形式为GMT+08:00
 
Z -- 时区
表现形式为+0800

NSDateFormatter的两个最实用的方法是dateFromString和stringFromDate,前者将一个字符串经过格式化后变成NSDate对象,后者将NSDate对象格式化成字符串。

在调用setDateFormat设置格式化字符串时,可以加入一些别的字符串,用单引号来引入,例如:

[formatter setDateFormat:@"yyyy-MM-dd 'some ''special'' string' HH:mm:ss"];

使用NSDateFormatter转换时间字符串时,默认的时区是系统时区,例如在中国一般都是北京时间(+8),如果直接转换会导致结果相差8小时,所以一般的做法是先指定时区为GMT标准时间再转换,例如:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];

NSDateComponents *compt = [[NSDateComponents alloc] init];
[compt setYear:2013];
[compt setMonth:3];
[compt setDay:13];
[compt setHour:1];
[compt setMinute:55];
[compt setSecond:28];

NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date = [calendar dateFromComponents:compt];
NSLog(@"%@",date);
NSString *str = [formatter stringFromDate:date];
NSLog(@"%@",str);




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值