码迷,mamicode.com
首页 > 移动开发 > 详细

获取当前时间---年月日时分秒------iOS

时间:2015-07-01 11:53:11      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

方式一:XXXX年-XX月-XX日  XX时:XX分:XX秒的格式

- (IBAction)LoginAction:(UIButton *)sender

{

   
    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秒的格式  
- (IBAction)LoginAction:(UIButton *)sender{

  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 =(int) [dateComponent year];
    int month = (int) [dateComponent month];
    int day = (int) [dateComponent day];
    int hour = (int) [dateComponent hour];
    int minute = (int) [dateComponent minute];
    int second = (int) [dateComponent second];
    
    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);
}

    

获取当前时间---年月日时分秒------iOS

标签:

原文地址:http://www.cnblogs.com/dongiosblogs/p/4612749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!