iOS 計算某個時間到現在是多少月/天/時的代碼
傳入一個NSString類型的日期
格式如newsDate = @"2013-08-09 17:01";
或者newsDate = @"2013/08/09 17:01";
返回如果有一個月,就不返回天,依次類推。
-(NSString *)getUTCFormateDate:(NSString *)newsDate { // newsDate = @"2013-08-09 17:01"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"]; NSLog(@"newsDate = %@",newsDate); NSDate *newsDateFormatted = [dateFormatter dateFromString:newsDate]; NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; [dateFormatter setTimeZone:timeZone]; NSDate* current_date = [[NSDate alloc] init]; NSTimeInterval time=[current_date timeIntervalSinceDate:newsDateFormatted];//間隔的秒數 int month=((int)time)/(3600*24*30); int days=((int)time)/(3600*24); int hours=((int)time)%(3600*24)/3600; int minute=((int)time)%(3600*24)/60; NSLog(@"time=%d",(double)time); NSString *dateContent; if(month!=0){ dateContent = [NSString stringWithFormat:@"%@%i%@",@" ",month,@"個月前"]; }else if(days!=0){ dateContent = [NSString stringWithFormat:@"%@%i%@",@" ",days,@"天前"]; }else if(hours!=0){ dateContent = [NSString stringWithFormat:@"%@%i%@",@" ",hours,@"小時前"]; }else { dateContent = [NSString stringWithFormat:@"%@%i%@",@" ",minute,@"分鐘前"]; } // NSString *dateContent=[[NSString alloc] initWithFormat:@"%i天%i小時",days,hours]; [current_date release]; [dateFormatter release]; return dateContent; }
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!