获取当前时间

- (void)getDateOne

{

    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];


    NSString *DateTime = [formatter stringFromDate:date];


    NSLog(@"%@============年-月-日  时:分:秒=====================",DateTime);

}

  方式二:XXXX年-X月-X日  XX时:XX分:XX秒的格式  
- (void)getDateTwo

  NSDate *now = [NSDate date];
    NSLog(@"now date is: %@", now);
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = 

NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;


    NSInteger year = [dateComponent year];
    NSInteger month =  [dateComponent month];
    NSInteger day = [dateComponent day];
    NSInteger hour =  [dateComponent hour];
    NSInteger minute =  [dateComponent minute];
    NSInteger second = [dateComponent second];

    
    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);
     //字符串的转化并且拼接
      NSString *yearstr=[NSString stringWithFormat:@"%ld-",(long)year];
      NSString *monthstr=[NSString stringWithFormat:@"%ld-",(long)month];
     NSString *daystr=[NSString stringWithFormat:@"%ld ",(long)day];
     NSString *hourstr=[NSString stringWithFormat:@"%ld:",(long)hour];
    NSString *minutestr=[NSString stringWithFormat:@"%ld:",(long)minute];
    NSString *secondstr=[NSString stringWithFormat:@"%ld",(long)second];
    //字符串开始拼接
    NSString *allstr=[yearstr stringByAppendingString:monthstr];
    NSString *allstr1=[allstr stringByAppendingString:daystr];
    NSString *allstr2=[allstr1 stringByAppendingString:hourstr];
    NSString *allstr3=[allstr2 stringByAppendingString:minutestr];
    NSString *DateTime=[allstr3 stringByAppendingString:secondstr];
    NSLog(@"最后年月日时分秒拼接的结果=====%@",DateTime);

    
}

posted @ 2017-03-21 09:37  昊天科技  阅读(110)  评论(0编辑  收藏  举报