Recently in the project, you need to turn back the background time into a few seconds ago, a few ago, a few hours ago, a few days ago and other formats; the time format returned in the background is: 2015-07-30 09:36:10, you need to compare the current time with the return time, and finally show a few seconds ago, a few ago, A few hours ago, a few days before the form.
1. Because the returned time is a string format, it is first converted to a timestamp
The string is converted to timestamp function Getdatetimestamp (datestr) { return Date.parse (Datestr.replace (/-/gi, "/"));}
2. Compare the returned timestamp to the current timestamp and convert it to a few seconds ago, a few ago, a few hours ago, a few days ago.
function Getdatediff (datestr) {var publishtime = Getdatetimestamp (datestr)/1000, D_seconds, D_minutes, D_hours, d_days, TimeNow = parseint (new date (). GetTime ()/1000), d, date = new Date (publ ishtime*1000), Y = Date.getfullyear (), M = Date.getmonth () + 1, D = Date.getdate (), H = date.g Ethours (), M = Date.getminutes (), S = date.getseconds (); Less than 10 in front of 0 if (M <) {m = ' 0 ' + m; } if (d <) {d = ' 0 ' + D; } if (H <) {h = ' 0 ' + H; } if (M <) {m = ' 0 ' + m; } if (S <) {s = ' 0 ' + s; } d = Timenow-publishtime; D_days = parseint (d/86400); D_hours = parseint (d/3600); D_minutes = parseint (D/60); D_seconds = parseint (d); if (d_days > 0 && d_days < 3) {return d_days + ' days ago '; }else if (d_days <= 0 && d_hours > 0) {return d_hours + ' hour ago '; }else if (d_hours <= 0 && d_minutes > 0) {return d_minutes + ' minutes ago '; }else if (D_seconds <) {if (d_seconds <= 0) {return ' just published '; }else {return d_seconds + ' seconds ago '; }}else if (d_days >= 3 && d_days <) {return m + '-' + D + ' ' + H + ': ' + M; }else if (d_days >=) {return Y + '-' + M + '-' + D + ' ' + H + ': ' + M; }}
3. How to use:
DATESTR: Returns the time string, formatted as: 2015-07-30 09:36:10
The converted result is var str = Getdatediff (DATESTR);//Output results Console.log (str) on the console;
JS converts the time of the string format to a few seconds ago, a few ago, a few hours ago, a few days ago and other formats