• 自学iOS-获取当前时间


    NSDate *  senddate=[NSDate date];  
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];  
    
    [dateformatter setDateFormat:@"YYYYMMdd"];  
    
    NSString *  locationString=[dateformatter stringFromDate:senddate];    
    
    NSLog(@"locationString:%@",locationString);
    
     [dateformatter release]; //这个有问题,显示日期不对

    关大叔的写法

    01    //获取当前时间
    02    NSDate *now = [NSDate date];
    03    NSLog(@”now date is: %@”, now);
    04
    05    NSCalendar *calendar = [NSCalendar currentCalendar];
    06    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    07    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    08     
    09    int year = [dateComponent year];
    10    int month = [dateComponent month];
    11    int day = [dateComponent day];
    12    int hour = [dateComponent hour];
    13    int minute = [dateComponent minute];
    14    int second = [dateComponent second];
    15
    16    NSLog(@”year is: %d”, year);
    17    NSLog(@”month is: %d”, month);
    18    NSLog(@”day is: %d”, day);
    19    NSLog(@”hour is: %d”, hour);
    20    NSLog(@”minute is: %d”, minute);
    21    NSLog(@”second is: %d”, second);

    获取星期几(好用的)可以获取:年、月、日、星期几

       NSDate *datet = [NSDate date];//现在时间
        NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"Sunday", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
        
        NSCalendar *calendars = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        
        NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
        
        [calendars setTimeZone: timeZone];
        
        NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
        
        NSDateComponents *theComponents = [calendars components:calendarUnit fromDate:datet];
        
        NSInteger unitFlagss = NSCalendarUnitYear |
        NSCalendarUnitMonth |
        NSCalendarUnitDay |
        NSCalendarUnitWeekday |
        NSCalendarUnitHour |
        NSCalendarUnitMinute |
        NSCalendarUnitSecond;
        
        theComponents = [calendars components:unitFlagss fromDate:datet];
        int week = [theComponents weekday];
        int year=[theComponents year];
        int month = [theComponents month];
        int day = [theComponents day];
        
        NSLog(@"%d年%d月",year,month);
        NSLog(@"%d",day);
        
        NSLog(@"xingqi%@",[weekdays objectAtIndex:theComponents.weekday]);
  • 相关阅读:
    Linux下批处理文件
    linux代码端启动终端
    ubuntu截图
    Ubuntu安装多个版本的Opencv
    Ubuntu双系统启动卡死
    Ubuntu14.04运行lsdslam与问题解决
    js懒加载
    公众号开发-获取用户信息
    ClipboardJS 复制文本功能
    css3 Gradient线性渐变详解
  • 原文地址:https://www.cnblogs.com/zhaixing/p/5429283.html
Copyright © 2020-2023  润新知