欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

获取当前时间、年份、月份、日期等

程序员文章站 2022-06-07 12:36:35
...
- (void)getCurrentDate {
//    获得时间对象
//    NSDate *date = [NSDate date];
//    // 获得系统的时区
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    // 以秒为单位返回当前时间与系统格林尼治时间的差
//    NSTimeInterval time = [zone secondsFromGMTForDate:date];
//    // 然后把差的时间加上,就是当前系统准确的时间
//    NSDate *nowDate = [date dateByAddingTimeInterval:time];
//    NSLog(@"now date is: %@", nowDate);
    
    //获取当前时间
    NSDate *now = [NSDate date];
    //NSLog(@"now date is: %@", now);

    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour |  NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday;
        NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSLog(@"dateComponent is :%@", dateComponent);
    
    NSInteger year = [dateComponent year];
    NSInteger month = [dateComponent month];
    NSInteger day = [dateComponent day];
    NSInteger hour = [dateComponent hour];
    NSInteger minute = [dateComponent minute];
    NSInteger second = [dateComponent second];
    NSInteger weekday = [dateComponent weekday];
    
    NSLog(@"year is: %ld", (long)year);
    NSLog(@"month is: %ld", (long)month);
    NSLog(@"day is: %ld", (long)day);
    NSLog(@"hour is: %ld", (long)hour);
    NSLog(@"minute is: %ld", (long)minute);
    NSLog(@"second is: %ld", (long)second);
    NSLog(@"weekday is: %ld", (long)weekday);
}