100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 获取当前时间---年月日时分秒------iOS

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

时间:2024-01-28 19:52:59

相关推荐

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

方式一: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);

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。