获取当前日期

1.    //获取当前时间,日期

    NSDate *dateTime = [NSDate date];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"YYYY/MM/dd"];

    NSString *dateString = [dateFormatter stringFromDate:dateTime];

        NSLog(@"dateString:%@",dateString);

2.

    NSDate *date = [NSDate date];//这个是NSDate类型的日期,所要获取的年月日都放在这里;

    NSCalendar *cal = [NSCalendar currentCalendar];

    unsigned int unitFlags = NSCalendarUnitYear|NSCalendarUnitMonth| NSCalendarUnitDay;//这句是说你要获取日期的元素有哪些。获取年就要写NSYearCalendarUnit,获取小时就要写NSHourCalendarUnit,中间用|隔开;

    NSDateComponents *d = [cal components:unitFlags fromDate:date];//把要从date中获取的unitFlags标示的日期元素存放在NSDateComponents类型的d里面; //然后就可以从d中获取具体的年月日了;

    NSInteger year = [d year];

    NSInteger month = [d month];

    NSInteger day = [d day];

    NSLog(@"%ld",year);

    NSLog(@"%ld",month);

    NSLog(@"%ld",day);

posted @ 2016-07-06 16:37  柳仙慧子  阅读(144)  评论(0编辑  收藏  举报