iOS---获取系统时间,年月日

 //现在时间,你可以输出来看下是什么格式

    NSDate *date = [NSDate date];

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

    //设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

    [forMatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSString *dateStr = [forMatter stringFromDate:date];

    NSLog(@"dateStr =  %@",dateStr);

    

    

//        //获取当前时间

//        NSDate *now = [NSDate date];

//        NSLog(@" now date is: %@ ",now);

//

//        NSCalendar *calendar = [NSCalendar currentCalendar];

//        NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

//        NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];

//

//        int year = [dateComponent year];

//        int month = [dateComponent month];

//        int day = [dateComponent day];

//        int hour = [dateComponent hour];

//        int minute = [dateComponent minute];

//        int second = [dateComponent second];

//

//    NSLog(@" year is: %d ",year);

//    NSLog(@" month is: %d ",month);

//    NSLog(@" day is: %d ",day);

//    NSLog(@" hour is: %d ",hour);

//    NSLog(@" minute is: %d ",minute);

//    NSLog(@" second is: %d ",second);

    

    

    // 定义一个遵循某个历法的日历对象 NSGregorianCalendar国际历法(iOS 8之前的,之后用NSCalendarIdentifierGregorian)

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    

    // 通过已定义的日历对象,获取某个时间点的NSDateComponents表示,并设置需要表示哪些信息(NSYearCalendarUnit, NSMonthCalendarUnit, NSDayCalendarUnit等)

    NSDateComponents *comps = [[NSDateComponents alloc] init];

    NSInteger unitFlags = NSCalendarUnitEra |

    NSCalendarUnitYear |

    NSCalendarUnitMonth |

    NSCalendarUnitDay |

    NSCalendarUnitHour |

    NSCalendarUnitMinute |

    NSCalendarUnitSecond |

    NSCalendarUnitWeekday |

    NSCalendarUnitWeekdayOrdinal |

    NSCalendarUnitQuarter |

    NSCalendarUnitWeekOfMonth |

    NSCalendarUnitWeekOfYear |

    NSCalendarUnitYearForWeekOfYear |

    NSCalendarUnitNanosecond |

    NSCalendarUnitCalendar |

    NSCalendarUnitTimeZone;

    comps = [calendar components:unitFlags fromDate:[NSDate date]];

    

    NSLog(@"era(世纪): %li", (long)comps.era);

    NSLog(@"year(年份): %li", (long)comps.year);

    NSLog(@"quarter(季度):%li", (long)comps.quarter);

    NSLog(@"month(月份):%li", (long)comps.month);

    NSLog(@"day(日期):%li", (long)comps.day);

    NSLog(@"hour(小时):%li", (long)comps.hour);

    NSLog(@"minute(分钟):%li", (long)comps.minute);

    NSLog(@"second(秒):%li", (long)comps.second);

    

    //    Sunday:1, Monday:2, Tuesday:3, Wednesday:4, Thursday:5, Friday:6, Saturday:7

    NSLog(@"weekday(星期):%li", (long)comps.weekday);


你可能感兴趣的:(iOS--时间)