Javascript and jquery are examples of codes that show time difference several minutes ago, several hours ago, or a few days ago. _ javascript tips-JS tutorial

Source: Internet
Author: User
On the Sina Weibo homepage, you can see that the time displayed after each microblog is not in the standard year-month-day format, but the time difference after conversion, for example: published five minutes ago and two hours ago, similar functions are more intuitive and user-friendly than the standard time display format. You can use JavaScript to achieve the following functions:

I. javascript function implementation:
Instance 1:

The Code is as follows:


// JavaScript Functions:
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 window is displayed.
// Alert ("the end date cannot be earlier 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 = "posted on" + parseInt (monthC) + "Months Ago ";
}
Else if (weekC> = 1 ){
Result = "posted on" + parseInt (weekC) + "weeks ago ";
}
Else if (dayC> = 1 ){
Result = "posted on" + parseInt (dayC) + "Days Ago ";
}
Else if (hourC> = 1 ){
Result = "posted on" + parseInt (hourC) + "Hours Ago ";
}
Else if (minC> = 1 ){
Result = "posted on" + parseInt (minC) + "Minutes Ago ";
} Else
Result = "just published ";
Return result;
}

If the time format you get is not a timestamp, you can use the following JavaScript function to convert the string to a timestamp. The function of this function is equivalent to the strtotime of the js version:

The Code is as follows:


// Js function code: converts a string to a timestamp
Function getDateTimeStamp (dateStr ){
Return Date. parse (dateStr. replace (/-/gi ,"/"));
}

Instance 2:

The Code is as follows:


Script
Function jsDateDiff (publishTime ){
Var d_minutes, d_hours, d_days;
Var timeNow = parseInt (new Date (). getTime ()/1000 );
Var d;
D = timeNow-publishTime;
D_days = parseInt (d/86400 );
D_hours = parseInt (DS/3600 );
D_minutes = parseInt (d/60 );
If (d_days> 0 & d_days <4 ){
Return d_days + "Days Ago ";
} Else if (d_days <= 0 & d_hours> 0 ){
Return d_hours + "Hours Ago ";
} Else if (d_hours <= 0 & d_minutes> 0 ){
Return d_minutes + "Minutes Ago ";
} Else {
Var s = new Date (publishTime * 1000 );
// S. getFullYear () + "year ";
Return (s. getMonth () + 1) + "month" + s. getDate () + "day ";
}
}
Script

Ii. jquery plug-in implementation

HTML code:

The Code is as follows:


">

Call code:

The Code is as follows:


JQuery ("span. timeago"). timeago ();

Plug-in source code:

The Code is 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 );
} 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: "",
SuffixFromNow: "from now ",
Seconds: "1 minute ",
Minute: "1 minute ",
Minutes: "% d minutes ",
Hour: "1 hour ",
Hours: "% d Hour ",
Day: "1 day ",
Days: "% d days ",
Month: "January ",
Months: "% d month ",
Year: "1 year ",
Years: "% d ",
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 secondds = 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 <45 & substitute ($ l. seconds, Math. round (seconds) |
Seconds <90 & substitute ($ l. minute, 1) |
Minutes <45 & substitute ($ l. minutes, Math. round (minutes) |
Minutes <90 & substitute ($ l. hour, 1) |
Hours <24 & substitute ($ l. hours, Math. round (hours) |
Hours <42 & substitute ($ l. day, 1) |
Days <30 & substitute ($ l. days, Math. round (days) |
Days <45 & 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)/, "$1 $2"); //-->-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 well with HTML5 in IE
Return $ (elem). get (0). tagName. toLowerCase () = "time"; // $ (elem). is ("time ");
}
});

// Functions that can be called via $ (el). timeago ('action ')
// Init is default when no action is given
// 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. 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 ");
}
// Each 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 (inWords (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 ");
}));

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.