第08天OC语言(14):NSCalendar

2017-07-26  本文已影响36人  liyuhong
须读:看完该文章你能做什么?

NSCalendar的基本使用

学习前:你必须会什么?(在这里我已经默认你具备C语言的基础了)

适合所有人,不需要懂的什么

注:(小白直接上手)

一、本章笔记
一、NSCalendar  日历类
    1.初始化
        @property (class, readonly, copy) NSCalendar *currentCalendar; // user's preferred calendar
    2.获取当前时间的年月日 时分秒
        - (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)date;
    3.比较两个时间之间的差值,比较相差多少年 多少月 多少日 多少时 多少分 多少秒
        - (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSCalendarOptions)opts;

二、code
main.m
#pragma mark 14-NSCalendar

#pragma mark - 代码
#import <Foundation/Foundation.h>
#pragma mark 类

#pragma mark - main函数
int main(int argc, const char * argv[])
{
#pragma 1.获取当前时间的年月日 时分秒
    // 获取当前时间
    NSDate *now = [NSDate date];
    NSLog(@"now = %@",now);
    // 日历
    NSCalendar *calendar1 = [NSCalendar currentCalendar];
    
    // 利用日历类 从当前时间对象中获取 年月日时分秒(单独获取出来)
    // 从一个时间里面获取 他的组成成员(年月日 时分秒)
    // components : 参数的含义是 : 问你需要获取什么?
    // 一般情况下 如果一个方法接收一个参数,这个参数是一个枚举, 那么可以通过|符号,连接多个枚举值
    NSCalendarUnit type = NSCalendarUnitYear |
                            NSCalendarUnitMonth |
                            NSCalendarUnitDay |
                            NSCalendarUnitHour |
                            NSCalendarUnitMinute |
                            NSCalendarUnitSecond;
    NSDateComponents *cmps =  [calendar1 components:type fromDate:now];
    NSLog(@"year = %ld",cmps.year);
    NSLog(@"month = %ld",cmps.month);
    NSLog(@"day = %ld",cmps.day);
    NSLog(@"hour = %ld",cmps.hour);
    NSLog(@"minute = %ld",cmps.minute);
    NSLog(@"second = %ld",cmps.second);

    
#pragma 2.比较两个时间之间的差值,比较相差多少年 多少月 多少日 多少时 多少分 多少秒
    // 过去的时间
    NSString *str = @"2017-07-21 08:12:16 +0000";
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init];
    formatter1.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
    NSDate *date1 = [formatter1 dateFromString:str];
    // 当前的时间
    NSDate *now1 = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    // 2.获取当前时区 和 指定时间的时间差
    NSInteger seconds =  [zone secondsFromGMTForDate:now];
    NSLog(@"seconds = %lu",seconds);
    now1 = [now1 dateByAddingTimeInterval:seconds];
    NSLog(@"date = %@",date1);
    NSLog(@"now1 = %@",now1);

    // 比较两个时间
    NSCalendar *calendar2 = [NSCalendar currentCalendar];
    NSDateComponents *cmps1 = [calendar2 components:type fromDate:date1 toDate:now1 options:0];
    NSLog(@"%ld年%ld月%ld日%ld时%ld分%ld秒",cmps1.year,cmps1.month,cmps1.day,cmps1.hour,cmps1.minute,cmps1.second);
    
    return 0;
}

上一篇 下一篇

猜你喜欢

热点阅读