In the open-source Chinese client, whether it is a comprehensive article, a question in the Q & A, or a moving talk, each article will be followed by a comment with time, for example, "10 minutes ago", "2 hours ago", "5 days ago", or "-2-9", these times are mandatory in many applications, in order to give the user a sense of time, know that the information is the latest, and also convenient to view the previous information based on time;
The time format parsed from the API is yyyy-mm-dd hh: mm: SS (for example, 09:51:22 ), after obtaining the article time on the API, it is obtained through algorithm conversion and the tool of the client source code. m + (nsstring *) intervalsincenow: (nsstring *) thedate to implement this method: if the information is displayed for minutes before 1 hour, the information within one day is displayed for hours, display by day within 10 days, and display by posting time outside 10 days:
+ (Nsstring *) intervalsincenow: (nsstring *) thedate {nsdateformatter * Date = [[nsdateformatter alloc] init]; [date setdateformat: @ "yyyy-mm-dd hh: mm: SS "]; nsdate * D = [date datefromstring: thedate]; nstimeinterval late = [d timeintervalsince1970] * 1; nsdate * dat = [nsdate datewithtimeintervalsincenow: 0]; nstimeinterval now = [dat timeintervalsince1970] * 1; nsstring * timestring = @ ""; nstimeinterval CHA = now-late; // post within one hour if (CHA/3600 <1) {If (CHA/60 <1) {timestring = @ "1";} else {timestring = [nsstring stringwithformat: @ "% F", CHA/60]; timestring = [timestring substringtoindex: timestring. length-7];} timestring = [nsstring stringwithformat: @ "% @ Minutes Ago", timestring];} // else if (CHA/3600> 1 & CHA/86400 <1) {timestring = [nsstring stringwithformat: @ "% F ", CHA/3600]; timestring = [timestring substringtoindex: timestring. length-7]; timestring = [nsstring stringwithformat: @ "% @ hour before", timestring];} // else if (CHA/86400> 1 & CHA/864000 <1) {timestring = [nsstring stringwithformat: @ "% F ", CHA/86400]; timestring = [timestring substringtoindex: timestring. length-7]; timestring = [nsstring stringwithformat: @ "% @ days ago", timestring];} // The posting time is greater than 10 days. else {// timestring = [nsstring stringwithformat: @ "% d-%"] nsarray * array = [thedate componentsseparatedbystring: @ ""]; // return [array objectatindex: 0]; timestring = [array objectatindex: 0];} return timestring ;}
This code can be used directly in your own project, and the returned timestring is the time required for the time period;
Demo: https://github.com/XFZLDXF/MyDemo.git