Data的使用

2018-01-13  本文已影响0人  CreateTian

(一) 获取NSDate的当前年月日

  1. NSDateFormat获取
NSDate *date =[NSDate date];//简书 FlyElephant
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

[formatter setDateFormat:@"yyyy"];
NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
[formatter setDateFormat:@"MM"];
NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
[formatter setDateFormat:@"dd"];
NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
  1. NSDateComponents获取
NSDate  *currentDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];

NSInteger year=[components year];
NSInteger month=[components month];
NSInteger day=[components day];

(二)获取当前时间

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
//现在时间,你可以输出来看下是什么格式

NSDate *datenow = [NSDate date];
//将nsdate按formatter格式转成nsstring
NSString *currentTimeString = [formatter stringFromDate:datenow];
上一篇下一篇

猜你喜欢

热点阅读