JS, jquery to achieve a few minutes ago, a few hours ago, a few days before the time difference shows the code instance

Source: Internet
Author: User
Tags datetime trim

  on Sina Weibo homepage see the time shown behind each Weibo is not the standard year-month-day format, instead, the time difference between the conversion, such as: Published 5 minutes ago, published in "2 hours ago", compared to the standard display format, seemingly more intuitive and humane

To achieve similar functions, using JS can be implemented as follows:   A, JavaScript function implementation: Example 1:     Code as follows://javascript function: var minute = 1000 * 60; var hour = minute * 60; var day = hour * 24; var halfamonth = day * 15; var month = day * 30; function Getdatediff (datetimestamp) {var now = new Date (). GetTime (); var diffvalue = Now-datetimestamp; if (diffvalue ; 0) { //If the date does not match the pop-up window to tell the  //alert ("End date cannot be less than the start date!") ");   var monthc =diffvalue/month; var weekc =diffvalue/(7*day); var dayc =diffvalue/day; var hourc =diffvalue/hour; var MinC =diffvalue/minute; if (monthc>=1) { result= "published in" + parseint (MONTHC) + "months ago";  }  else if (weekc>=1) { result= "published on" + parseint (WEEKC) + "weeks ago"; &NBSP}  else if (dayc>=1) { result= "published on" + parseint (DAYC) + "days before";    else if (hourc>=1) {  Result= "published in" + parseint (HOURC) + "an hour ago"; &NBSP}  else if (minc>=1) { result= "published in" + parseint (MinC) + "minutes ago";  }else  result= "just published"; return result; }     If you get the time format is not a timestamp, you can useThe following JavaScript function converts a string to a timestamp, the function of which is equivalent to the JS version of Strtotime:     Code as follows://js function code: string conversion to timestamp function Getdatetimestamp ( DATESTR) { return date.parse (datestr.replace (/-/gi, "/")}     Instance 2:   Code as follows: <script>   &N Bsp    function Jsdatediff (publishtime) {           var d_minutes,d_hours,d_days; nbsp          var timenow = parseint (new Date (). GetTime ()/1000);            VAR D;            d = timenow-publishtime;            d_days = parseint (d/86400);            d_hours = parseint (d/3600);            d_minutes = parseint (D/60);            if (d_days>0 && d_days<4) {               return d_days+ "days ago";           }else if (d_days<=0 &&Amp d_hours>0) {               return d_hours+ "hours ago";        &NB Sp  }else if (d_hours<=0 && d_minutes>0) {               return D_ minutes+ "Minutes ago";           }else{               var s = new Date (PU blishtime*1000);               //S.getfullyear () + "year";         return (S.getmonth () +1) + "month" +s.getdate () + "Day";            {      }        </script>     II, jquery plug-in implementation   HTML code:     Code as follows: <span class= "Time Timeago" title= "<fmt:formatdate value=" ${ Comment.createat} "pattern=" Yyyy-mm-dd HH:mm:ss "/>" ></span>     calling code:     Code as follows: JQuery ( "Span.timeago"). Timeago ();     Plugin Source:       Code as follows: (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); &N Bsp  } else if (typeof timestamp = = "string") {      return inwords ($.timeago.parse (timestamp));    } else if (typeof timestamp = = "number") {      return inwords (new Date (timestamp));   &NBSP ; else {      return inwords ($.timeago.datetime (timestamp));    }  };   var $t = $.timeago;     $.extend ($.timeago, {    settings: {      refreshmillis:60000,     &NB Sp Allowfuture:false,       Localetitle:false,       cutoff:0       strings: {        Prefixago:null,         Prefixfromnow:null,         Suffixago: "Pre",         Suffixfromnow: "From Now", & nbsp       seconds: "1 minutes",         minute: "1 minutes",         minutes: "%d minutes ",         Hour:" 1 hours ",         Hours:"%d hours ",         Day:" 1 Day,         days: "%d Day",         Month: "January",    ,     months: "%d months",         Year: "1 Years",         years: "%d Years",         WordS Eparator: "        numbers: []      }    },     INWORDS:FUNCT Ion (Distancemillis) {      var $l = this.settings.strings       var prefix = $l. Prefixago;     &nbsp var suffix = $l. Suffixago;       if (this.settings.allowFuture) {        if (Distancemillis < 0) {  &nbs P       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 = $.ISF Unction (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; days, 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);     &NBS P s = S.replace (/.d+/, ""); Remove milliseconds       s = s.replace (/-/, "/"). Replace (/-/, "/");       s = s.replace (/t/, ""). Replace (/z/, "UTC");       s = s.replace (/([+-]dd):? ( DD)/, "$1$2"); -04:00-> -0400       return new Date (s);    },     datetime:function (elem) {      var iso8601 = $t. Istime (elem)? $ (elem). att R ("datetime"): $ (elem). attr ("title");       return $t. Parse (iso8601);    },     istime:function (elem) {     //JQuery ' s ' are () ' doesn ' t play-with HTM L5 in IE       return $ (elem). (0). Tagname.tolowercase () = = "Time"; $ (Elem). Is (' time ');    }  });    //functions can be called via $ (EL). Timeago (' action ')  //init are default when no action is give n  //functions are called with context of a single element   var functions = {    init:function () {       var refresh_el = $.proxy (refresh, this);       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. Pars E ($t. Istime (This) $ (a). attr ("datetime"): $ (this). attr ("title"))};       Refresh.apply(this);    }  };     $.fn.timeago = function (action, options) {    var fn = action Functions[action]: Functions.ini T     if (!FN) {      throw new Error ("Unknown function name" + action + "' for Timeago");   &N Bsp }    //each over objects requested function     This.each (function () {  &NBSP ;   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. Cut Off) {        $ (this). Text (Inwords (data.datetime);      }    }   &NB Sp 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 (' Timea Go '). datetime.tolocalestring ());      } else if (text.length > 0 &&!) ( $t. Istime (Element) && element.attr ("title")) {        element.attr ("title", text);   & nbsp  }    }     return Element.data ("Timeago");  }     function inwords (date) {    return $t. Inwords (distance date);  }     FU Nction Distance (date) {    return (new Date (). GetTime ()-date.gettime ());  }    //fix for IE 6 suckage   document.createelement ("abbr");   Document.createelement ("Time"); }));

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.