获取当前时间的方法 返回值中的字段为 年 月 日 时 分 秒 周
1 -(NSMutableDictionary*)getTodayTimeDictionary 2 { 3 NSInteger year,month,day,hour,min,sec,week;//年月日时分秒周 4 5 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 6 7 NSDate *now = [NSDate date];; 8 9 NSDateComponents *comps = [[NSDateComponents alloc] init];10 11 NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |12 13 NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;14 15 comps = [calendar components:unitFlags fromDate:now];16 17 year = [comps year];//年18 19 month = [comps month];//月20 21 day = [comps day];//日22 23 hour = [comps hour];//时24 25 min = [comps minute];//分26 27 sec = [comps second];//秒28 29 week = [comps weekday];/*周 这里的1为周日 顺序为 1 2 3 4 5 6 730 周日 一 二 三 四 五 六*/31 //处理week 当week=1时,输出周日32 // week>1时,输出week-133 34 if (week>1)35 {36 week = week-1;37 }38 else39 {40 week = 7;41 }42 43 NSLog(@"现在是:%ld年%ld月%ld日 %ld时%ld分%ld秒 周%ld",(long)year,(long)month,(long)day,(long)hour,(long)min,(long)sec,(long)week);44 45 //封装在字典里,作为返回值返回46 NSMutableDictionary*dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:47 [NSString stringWithFormat:@"%ld",year],@"year",48 [NSString stringWithFormat:@"%ld",month],@"month",49 [NSString stringWithFormat:@"%ld",day],@"day",50 [NSString stringWithFormat:@"%ld",hour],@"hour",51 [NSString stringWithFormat:@"%ld",min],@"min",52 [NSString stringWithFormat:@"%ld",sec],@"sec",53 [NSString stringWithFormat:@"%ld",week],@"week",54 nil];55 //当值为个位数时,前面补个0 如:5月 补为05月;7分 补为07分。 年和周 不用处理56 if (month < 10)57 {58 [dict setValue:[NSString stringWithFormat:@"0%ld",month] forKey:@"month"];59 }60 if (day < 10)61 {62 [dict setValue:[NSString stringWithFormat:@"0%ld",day] forKey:@"day"];63 }64 if (hour < 10)65 {66 [dict setValue:[NSString stringWithFormat:@"0%ld",hour] forKey:@"hour"];67 }68 if (min<10)69 {70 [dict setValue:[NSString stringWithFormat:@"0%ld",min] forKey:@"min"];71 }72 if (sec<10)73 {74 [dict setValue:[NSString stringWithFormat:@"0%ld",sec] forKey:@"sec"];75 }76 NSLog(@"%@",dict);77 return dict;78 }
打印的信息为
现在是:2015年7月21日 14时5分48秒 周2
{
day = 21;
hour = 14;
min = 05;
month = 07;
sec = 48;
week = 2;
year = 2015;
}
用的时候,接收到返回值,读取字典对应key即可。
想获取关于 时间戳操作方法的 请点击