码迷,mamicode.com
首页 > 其他好文 > 详细

字符串转成NSDate类型,计算与当前时间的相差,年数,天数,时分秒

时间:2015-01-21 19:36:47      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

NSString *dateStr=@"2013-08-13 20:28:40";//传入时间
//将传入时间转化成需要的格式
NSDateFormatter *format=[[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *fromdate=[format dateFromString:dateStr];
NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
NSDate *fromDate = [fromdate  dateByAddingTimeInterval: frominterval];
NSLog(@"fromdate=%@",fromDate);
[format release];
//获取当前时间
NSDate *date = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
NSLog(@"enddate=%@",localeDate);
  
  
double intervalTime = [fromDate timeIntervalSinceReferenceDate] - [localeDate timeIntervalSinceReferenceDate];
  
long lTime = (long)intervalTime;
NSInteger iSeconds = lTime % 60;
NSInteger iMinutes = (lTime / 60) % 60;
NSInteger iHours = (lTime / 3600)$;
NSInteger iDays = lTime/60/60/24;
NSInteger iMonth = lTime/60/60/24/12;
NSInteger iYears = lTime/60/60/24/384;
  
NSLog(@"相差M年d月 或者 d日d时d分d秒", iYears,iMonth,iDays,iHours,iMinutes,iSeconds);
//该代码片段来自于: http://www.sharejs.com/codes/objectc/5099

 

字符串转成NSDate类型,计算与当前时间的相差,年数,天数,时分秒

标签:

原文地址:http://www.cnblogs.com/allanliu/p/4239617.html

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