Here is a summary of the JS implementation time to display a few days ago, a few hours ago or a few minutes before the common methods. Share to everyone for your reference. Specifically as follows:
Method One:
The personal practice is to save the timestamp, and then use the JQ plugin on the front end to do the conversion, such as Smart-time-ago
Method Two:
(through the Freemarker template) if you use the Freemarker template to write this, the other template analogy
Modify the conditions and output according to your own will, and pass your datetime in.
< #macro Timeline_dt datetime=.now>
< #assign ct = (. Now?long-datetime?long)/1000>
< #if CT GTE 31104000><#--n years ago-->${(ct/31104000) int} years ago
< #t >< #elseif CT GTE 2592000><#--n months ago-->${ (ct/2592000)? int} a month ago
< #t >< #elseif ct GTE 86400*2><#--n days ago-->${(ct/86400)? int} days ago
< #t >< #elseif Ct GTE 86400><#--1 days ago-->
< #t >< #elseif ct GTE 3600><#--n hours ago-->${(ct/ 3600)? int} hours ago
< #t >< #elseif CT gte 60><#--n minutes ago-->${(CT/60)? int} minutes ago
< #t >< #elseif CT gt 0><#--n seconds ago-->${ct?int {sec
< #t >< #else > Just
</#if >
</#macro >
Method Three:
Find a dedicated plugin Prettytime
public static void Main (string[] args) {
prettytime p = new Prettytime ();
System.out.println (P.format (Dateutils.adddays (New Date (), 2));
}
Method Four:
Custom Java methods:
private final static long minute = 60 * 1000;//1 minutes Private final static long hour = 60 * minute;//1 hours private final static long day = * hour;//1 days private final static long month = * day;//month private Final static long year = month;///** * Returns the date of the text description * * @param date * @return/public static String GETTIMEF
Ormattext (date date) {if (date = null) {return null;
Long diff = new Date (). GetTime ()-date.gettime ();
Long r = 0;
if (diff > year) {r = (diff/year);
Return r + "years ago";
} if (diff > month) {r = (diff/month);
Return R + "a month ago";
} if (diff > day) {r = (diff/day);
return r + "days Ago";
} if (diff > hour) {r = (diff/hour);
Return R + "an hour ago";
} if (diff > minute) {r = (Diff/minute);
return r + "minutes ago";
return "just"; }
Method Five:
Use JS plugin: (Original timeago.js)
Smart time Ago v0.1.0//Copyright, Terry Tai, pragmatic.ly//https://pragmatic.ly///licensed under the MIT
License.
Https://github.com/pragmaticly/smart-time-ago/blob/master/LICENSE (function () {var timeago;
Timeago = (function () {function Timeago (element, options) {this.startinterval = 60000;
This.init (element, options);
} TimeAgo.prototype.init = function (element, options) {this. $element = $ (element);
This.options = $.extend ({}, $.fn.timeago.defaults, options);
This.updatetime ();
return This.starttimer ();
};
TimeAgo.prototype.startTimer = function () {var self;
self = this;
return this.interval = setinterval (function () {return Self.refresh ();
}), This.startinterval);
};
TimeAgo.prototype.stopTimer = function () {return clearinterval (this.interval);
};
TimeAgo.prototype.restartTimer = function () {This.stoptimer ();
return This.starttimer ();
}; TimeAgo.prototype.refrEsh = function () {this.updatetime ();
return This.updateinterval ();
};
TimeAgo.prototype.updateTime = function () {var self;
self = this;
return this. $element. Findandself (This.options.selector). each (function () {var timeagoinwords;
Timeagoinwords = Self.timeagoinwords ($ (this). attr (self.options.attr));
return $ (this). html (timeagoinwords);
});
};
TimeAgo.prototype.updateInterval = function () {var filter, newesttime, Newesttimeinminutes, NEWESTTIMESRC; if (this. $element. Findandself (this.options.selector). length > 0) {if (This.options.dir = = ' up ') {filter =
": a";
else if (This.options.dir = = "Down") {filter = ': Last ';
NEWESTTIMESRC = this. $element. Findandself (This.options.selector). Filter (Filter). attr (this.options.attr);
Newesttime = This.parse (NEWESTTIMESRC);
Newesttimeinminutes = This.gettimedistanceinminutes (newesttime); if (newesttimeinminutes >= 0 && NewesTtimeinminutes <= && this.startinterval!== 60000) {this.startinterval = 60000;
return This.restarttimer (); else if (newesttimeinminutes >= && newesttimeinminutes <=-&& this.startinterval!== 60000 *
{This.startinterval = 60000 * 22;
return This.restarttimer (); else if (newesttimeinminutes >= && newesttimeinminutes <= 2519 && this.startinterval!== 60000
* {This.startinterval = 60000 * 30;
return This.restarttimer (); else if (newesttimeinminutes >= 2520 && this.startinterval!== 60000 * *) {This.startinterval =
60000 * 60 * 12;
return This.restarttimer ();
}
}
};
TimeAgo.prototype.timeAgoInWords = function (timestring) {var absoluttime;
Absoluttime = This.parse (timestring);
Return This.distanceoftimeinwords (absoluttime) + (This.options.lang.suffix);
}; TimeAgo.prototype.parse = function (iso86) {var timestr;
Timestr = $.trim (iso8601);
Timestr = Timestr.replace (/\.\d\d\d+/, "");
Timestr = Timestr.replace (/-/, "/"). Replace (/-/, "/");
Timestr = Timestr.replace (/t/, ""). Replace (/z/, "UTC"); TIMESTR = Timestr.replace (/[\+\-]\d\d) \:? (
\d\d)/, "$1$2");
return new Date (TIMESTR);
};
TimeAgo.prototype.getTimeDistanceInMinutes = function (absoluttime) {var timedistance;
Timedistance = new Date (). GetTime ()-absoluttime.gettime ();
Return Math.Round (Math.Abs (timedistance)/1000)/60);
};
TimeAgo.prototype.distanceOfTimeInWords = function (absoluttime) {var Dim;
Dim = This.gettimedistanceinminutes (Absoluttime);
if (Dim = = 0) {return "" + this.options.lang.prefixes.lt + "" + This.options.lang.units.minute;
else if (Dim = = 1) {return "1" + this.options.lang.units.minute;
else if (Dim >= 2 && Dim <=) {Return "+ Dim +" "+ this.options.lang.units.minutes; else IF (Dim >= && Dim <=) {return "" + This.options.lang.prefixes.about + "1" + this.options.lang.u
Nits.hour; else if (Dim >= && Dim <= 1439) {return "+ This.options.lang.prefixes.about +" "+ (Math.Round (DIM/60))
+ "" + this.options.lang.units.hours;
else if (Dim >= 1440 && Dim <= 2519) {return "1" + this.options.lang.units.day; else if (Dim >= 2520 && Dim <= 43199) {return "+ (Math.Round (dim/1440)) +" "+ This.options.lan
G.units.days; else if (Dim >= 43200 && Dim <= 86399) {return "" + This.options.lang.prefixes.about + "1" + this.
Options.lang.units.month; else if (Dim >= 86400 && Dim <= 525599) {return "+ (Math.Round (dim/43200)) +" "+ this.options.
Lang.units.months; else if (Dim >= 525600 && Dim <= 655199) {return "" + This.options.lang.prefixes.about + "1" + thi S.options.lang.units. year; else if (Dim >= 655200 && Dim <= 914399) {return "" + This.options.lang.prefixes.over + "1" + This
. options.lang.units.year; else if (Dim >= 914400 && Dim <= 1051199) {return "" + This.options.lang.prefixes.almost + "2" + t
His.options.lang.units.years; else {return "" + This.options.lang.prefixes.about + "" + (Math.Round (dim/525600)) + "" + this.options.lang.un
Its.years;
}
};
return Timeago;
})();
$.fn.timeago = function (options) {if (options = null) options = {};
Return This.each (function () {var $this, data;
$this = $ (this);
data = $this. Data ("Timeago");
if (!data) $this. Data ("Timeago", New Timeago (this, options));
if (typeof options = = ' String ') return data[options] ();
});
};
$.fn.findandself = function (selector) {return This.find (selector). Add (This.filter (selector));
};
$.fn.timeago.constructor = Timeago; $.fn.timeago.defaults = {selector: ' tIme.timeago ', attr: ' DateTime ', dir: ' Up ', Lang: {units: {second: "Second", Seconds: "Seconds",
minute: "Minute", Minutes: "Minutes", Hour: "Hour", Hours: "Hours", Day: ' Day ', Days: ' Days ', Month: "Month", Months: "Months", Year: "Year", Years: "Years"}, prefixes: {lt: "less
than a ", about:" About ", over:" Over ", almost:" Almost "}, suffix: ' ago '};
). Call (this);
Use JS plugin: (Modified version (Jane Yo version) timeago.js) in Chinese
(function (Factory) {if (typeof define = = ' function ' && define.amd) {//AMD.
Register as an anonymous module.
define ([' jquery '], factory);
else {//Browser Globals Factory (jQuery);
} (function ($) {$.timeago = function (timestamp) {if (timestamp instanceof Date) {return inwords (timestamp);
else if (typeof timestamp = = "string") {return inwords ($.timeago.parse (timestamp));
else if (typeof timestamp = = "Number") {return inwords (new Date (timestamp));
else {return inwords ($.timeago.datetime (timestamp));
}
};
var $t = $.timeago; $.extend ($.timeago, {settings: {refreshmillis:60000, Allowfuture:false, Localetitle:false, cutoff:
0, strings: {prefixago:null, Prefixfromnow:null, Suffixago: "Former", Suffixfromnow: "From Now", Seconds: "1 minutes", minute: "1 minutes", minutes: "%d minutes", hour: "1 hours", Hours: "%d hours", Day: "1 days", Da YS: "%d Days", MOnth: "January", Months: "%d months", Year: "1 Years", Years: "%d Years", Wordseparator: "", Numbers: []},
Inwords:function (Distancemillis) {var $l = this.settings.strings;
var prefix = $l. Prefixago;
var suffix = $l. Suffixago;
if (this.settings.allowFuture) {if (Distancemillis < 0) {prefix = $l. Prefixfromnow;
suffix = $l. Suffixfromnow;
} var seconds = Math.Abs (Distancemillis)/1000;
var minutes = seconds/60;
var hours = minutes/60;
var days = hours/24;
var years = days/365; function substitute (stringorfunction, number) {var string = $.isfunction (stringorfunction)? Stringorfunction (number
, distancemillis): stringorfunction; var value = ($l. Numbers && $l. Numbers[number]) | |
Number
Return String.Replace (/%d/i, value);
var words = seconds < && substitute ($l. seconds, Math.Round (seconds)) | | Seconds < && substitute ($l. minutE, 1) | |
Minutes < && substitute ($l. Minutes, Math.Round (minutes)) | |
Minutes < && substitute ($l. Hour, 1) | |
Hours < && substitute ($l. Hours, Math.Round (hours)) | |
Hours < && substitute ($l. Day, 1) | |
Days < && substitute ($l, math.round) | |
Days < && substitute ($l. Month, 1) | |
Days < 365 && substitute ($l. Months, Math.Round (DAYS/30)) | |
Years < 1.5 && substitute ($l. Year, 1) | |
Substitute ($l. Years, Math.Round (years)); var separator = $l. Wordseparator | |
"";
if ($l. wordseparator = = undefined) {separator = "";}
return $.trim ([prefix, Words, suffix].join (separator));
}, Parse:function (iso8601) {var s = $.trim (iso8601); s = S.replace (/\.\d+/, "");
Remove milliseconds s = s.replace (/-/, "/"). Replace (/-/, "/");
s = S.replace (/t/, ""). Replace (/z/, "UTC"); s = s.replace (/([\+\-]\d\d) \:? \d\d)/,"$1$2");
-04:00-> -0400 return new Date (s);
}, Datetime:function (elem) {var iso8601 = $t. Istime (elem)? $ (Elem). attr ("datetime"): $ (elem). attr ("title");
Return $t. Parse (iso8601); }, Istime:function (elem) {//JQuery ' s ' is () ' doesn ' t-play-with-HTML5 in IE return $ (elem). Get (0). tagName . toLowerCase () = = "Time";
$ (Elem). Is (' time ');
}
}); Functions that can are called via $ (EL). Timeago (' action ')//init is default at no action is given//functions AR E called with context of a single element var functions = {init:function () {var refresh_el = $.proxy (Refresh, t
His);
Refresh_el ();
var $s = $t. Settings;
if ($s. Refreshmillis > 0) {setinterval (Refresh_el, $s. Refreshmillis);
}, Update:function (time) {$ (this). Data (' Timeago ', {datetime: $t. Parse (Time)});
Refresh.apply (this); }, Updatefromdom:function () {$ (this). Data (' Timeago ', {datetime: $t. Parse ($t. Istime (This) $(this). attr (' DateTime '): $ (this). attr ("title")});
Refresh.apply (this);
}
};
$.fn.timeago = function (action, options) {var fn = action Functions[action]: Functions.init;
if (!FN) {throw new Error ("Unknown function name" + action + "' for Timeago");
//per over objects here and call the requested function This.each (function () {Fn.call (this, options);
});
return this;
};
function Refresh () {var data = Preparedata (this);
var $s = $t. Settings; if (!isnan (data.datetime)) {if $s. cutoff = 0 | | distance (data.datetime) < $s. Cutoff) {$ (this). Text (Inword
S (data.datetime));
} return this;
function Preparedata (element) {element = $ (element);
if (!element.data ("Timeago")) {Element.data ("Timeago", {datetime: $t. DateTime (Element)});
var text = $.trim (Element.text ());
if ($t. Settings.localetitle) {element.attr ("title", Element.data (' Timeago '). datetime.tolocalestring ()); } elsE if (text.length > 0 &&!) (
$t. Istime (Element) && element.attr ("title")) {element.attr ("title", text);
} return Element.data ("Timeago");
function Inwords (date) {return $t. Inwords (distance (date));
function distance (date) {return (new Date (). GetTime ()-date.gettime ());
//fix for IE6 suckage document.createelement ("abbr");
Document.createelement ("Time");
}));
The
wants this article to help you with your JavaScript programming.