longlongtimeago

更新时间:2022-11-27 15:45:15 阅读: 评论:0


2022年11月27日发(作者:stateoftheart)

js实现时间显⽰⼏天前、⼏⼩时前或者⼏分钟前的⽅法集

这⾥汇总了js实现时间显⽰⼏天前、⼏⼩时前或者⼏分钟前的常见⽅法。分享给⼤家供⼤家参考。具体如下:

⽅法⼀:

个⼈做法是保存时间戳,然后在前端⽤jq插件做转换,⽐如smart-time-ago

⽅法⼆:

(通过freemarker模板)如果⽤freemarker模板可以这样写,别的模板类推

根据⾃⼰的意愿修改条件和输出,把你的datetime传进去即可

<#macrotimeline_dtdatetime=.now>

<#assignct=(.now?long-datetime?long)/1000>

<#ifctgte31104000><#--n年前-->${(ct/31104000)?int}年前

<#t><#elifctgte2592000><#--n⽉前-->${(ct/2592000)?int}个⽉前

<#t><#elifctgte86400*2><#--n天前-->${(ct/86400)?int}天前

<#t><#elifctgte86400><#--1天前-->昨天

<#t><#elifctgte3600><#--n⼩时前-->${(ct/3600)?int}⼩时前

<#t><#elifctgte60><#--n分钟前-->${(ct/60)?int}分钟前

<#t><#elifctgt0><#--n秒前-->${ct?int}秒前

<#t><#el>刚刚

⽅法三:

找到⼀个专门的插件PrettyTime

publicstaticvoidmain(String[]args){

PrettyTimep=newPrettyTime();

n((s(newDate(),2)));

}

⽅法四:

⾃定义Java⽅法:

privatefinalstaticlongminute=60*1000;//1分钟

privatefinalstaticlonghour=60*minute;//1⼩时

privatefinalstaticlongday=24*hour;//1天

privatefinalstaticlongmonth=31*day;//⽉

privatefinalstaticlongyear=12*month;//年

/**

*返回⽂字描述的⽇期

*

*@paramdate

*@return

*/

publicstaticStringgetTimeFormatText(Datedate){

if(date==null){

returnnull;

}

longdiff=newDate().getTime()-e();

longr=0;

if(diff>year){

r=(diff/year);

returnr+"年前";

}

if(diff>month){

r=(diff/month);

returnr+"个⽉前";

}

if(diff>day){

r=(diff/day);

returnr+"天前";

}

if(diff>hour){

r=(diff/hour);

returnr+"个⼩时前";

}

if(diff>minute){

r=(diff/minute);

returnr+"分钟前";

}

return"刚刚";

}

⽅法五:

使⽤js插件:(原版的)

//SmartTimeAgov0.1.0

//Copyright2012,TerryTai,

///

//LicendundertheMITlicen.

///pragmaticly/smart-time-ago/blob/master/LICENSE

(function(){

varTimeAgo;

TimeAgo=(function(){

functionTimeAgo(element,options){

nterval=60000;

(element,options);

}

=function(element,options){

this.$element=$(element);

s=$.extend({},$.ts,options);

Time();

imer();

};

imer=function(){

varlf;

lf=this;

al=tInterval((function(){

h();

}),nterval);

};

mer=function(){

returnclearInterval(al);

};

tTimer=function(){

mer();

imer();

};

h=function(){

Time();

Interval();

};

Time=function(){

varlf;

lf=this;

returnthis.$dSelf(or).each(function(){

vartimeAgoInWords;

timeAgoInWords=oInWords($(this).attr());

return$(this).html(timeAgoInWords);

});

};

Interval=function(){

varfilter,newestTime,newestTimeInMinutes,newestTimeSrc;

if(this.$dSelf(or).length>0){

if(==="up"){

filter=":first";

}elif(==="down"){

filter=":last";

}

newestTimeSrc=this.$dSelf(or).filter(filter).attr();

newestTime=(newestTimeSrc);

newestTimeInMinutes=eDistanceInMinutes(newestTime);

if(newestTimeInMinutes>=0&&newestTimeInMinutes<=44&&nterval!==60000){

nterval=60000;

tTimer();

}elif(newestTimeInMinutes>=45&&newestTimeInMinutes<=89&&nterval!==60000*22){

nterval=60000*22;

tTimer();

}elif(newestTimeInMinutes>=90&&newestTimeInMinutes<=2519&&nterval!==60000*30){

nterval=60000*30;

tTimer();

}elif(newestTimeInMinutes>=2520&&nterval!==60000*60*12){

nterval=60000*60*12;

tTimer();

}

}

};

oInWords=function(timeString){

varabsolutTime;

absolutTime=(timeString);

ceOfTimeInWords(absolutTime)+();

};

=function(iso8601){

vartimeStr;

timeStr=$.trim(iso8601);

timeStr=e(/.ddd+/,"");

timeStr=e(/-/,"/").replace(/-/,"/");

timeStr=e(/T/,"").replace(/Z/,"UTC");

timeStr=e(/([+-]dd):?(dd)/,"$1$2");

returnnewDate(timeStr);

};

eDistanceInMinutes=function(absolutTime){

vartimeDistance;

timeDistance=newDate().getTime()-e();

(((timeDistance)/1000)/60);

};

ceOfTimeInWords=function(absolutTime){

vardim;

dim=eDistanceInMinutes(absolutTime);

if(dim===0){

return""++""+;

}elif(dim===1){

return"1"+;

}elif(dim>=2&&dim<=44){

return""+dim+""+s;

}elif(dim>=45&&dim<=89){

return""++"1"+;

}elif(dim>=90&&dim<=1439){

return""++""+((dim/60))+""+;

}elif(dim>=1440&&dim<=2519){

return"1"+;

}elif(dim>=2520&&dim<=43199){

return""+((dim/1440))+""+;

}elif(dim>=43200&&dim<=86399){

return""++"1"+;

}elif(dim>=86400&&dim<=525599){

return""+((dim/43200))+""+;

}elif(dim>=525600&&dim<=655199){

return""++"1"+;

}elif(dim>=655200&&dim<=914399){

return""++"1"+;

}elif(dim>=914400&&dim<=1051199){

return""++"2"+;

}el{

return""++""+((dim/525600))+""+;

}

};

returnTimeAgo;

})();

$.o=function(options){

if(options==null)options={};

(function(){

var$this,data;

$this=$(this);

data=$("timeago");

if(!data)$("timeago",newTimeAgo(this,options));

if(typeofoptions==='string')returndata[options]();

});

};

$.dSelf=function(lector){

(lector).add((lector));

};

$.uctor=TimeAgo;

$.ts={

lector:'o',

attr:'datetime',

dir:'up',

lang:{

units:{

cond:"cond",

conds:"conds",

minute:"minute",

minutes:"minutes",

hour:"hour",

hours:"hours",

day:"day",

days:"days",

month:"month",

months:"months",

year:"year",

years:"years"

},

prefixes:{

lt:"lessthana",

about:"about",

over:"over",

almost:"almost"

},

suffix:'ago'

}

};

}).call(this);

使⽤js插件:(改装版(简哟版))中⽂的

(function(factory){

if(typeofdefine==='function'&&){

//erasananonymousmodule.

define(['jquery'],factory);

}el{

//Browrglobals

factory(jQuery);

}

}(function($){

$.timeago=function(timestamp){

if(timestampinstanceofDate){

returninWords(timestamp);

}elif(typeoftimestamp==="string"){

returninWords($.(timestamp));

}elif(typeoftimestamp==="number"){

returninWords(newDate(timestamp));

}el{

returninWords($.me(timestamp));

}

};

var$t=$.timeago;

$.extend($.timeago,{

ttings:{

refreshMillis:60000,

allowFuture:fal,

localeTitle:fal,

cutoff:0,

strings:{

prefixAgo:null,

prefixFromNow:null,

suffixAgo:"前",

suffixFromNow:"fromnow",

conds:"1分钟",

minute:"1分钟",

minutes:"%d分钟",

hour:"1⼩时",

hours:"%d⼩时",

day:"1天",

days:"%d天",

month:"1⽉",

months:"%d⽉",

year:"1年",

years:"%d年",

wordSeparator:"",

numbers:[]

}

},

inWords:function(distanceMillis){

var$l=s;

varprefix=$Ago;

varsuffix=$Ago;

if(uture){

if(distanceMillis<0){

prefix=$FromNow;

suffix=$FromNow;

}

}

varconds=(distanceMillis)/1000;

varminutes=conds/60;

varhours=minutes/60;

vardays=hours/24;

varyears=days/365;

functionsubstitute(stringOrFunction,number){

varstring=$.isFunction(stringOrFunction)?stringOrFunction(number,distanceMillis):stringOrFunction;

varvalue=($s&&$s[number])||number;

e(/%d/i,value);

}

varwords=conds<45&&substitute($s,(conds))||

conds<90&&substitute($,1)||

minutes<45&&substitute($s,(minutes))||

minutes<90&&substitute($,1)||

hours<24&&substitute($,(hours))||

hours<42&&substitute($,1)||

days<30&&substitute($,(days))||

days<45&&substitute($,1)||

days<365&&substitute($,(days/30))||

years<1.5&&substitute($,1)||

substitute($,(years));

varparator=$parator||"";

if($parator===undefined){parator="";}

return$.trim([prefix,words,suffix].join(parator));

},

par:function(iso8601){

vars=$.trim(iso8601);

s=e(/.d+/,"");//removemilliconds

s=e(/-/,"/").replace(/-/,"/");

s=e(/T/,"").replace(/Z/,"UTC");

s=e(/([+-]dd):?(dd)/,"$1$2");//-04:00->-0400

returnnewDate(s);

},

datetime:function(elem){

variso8601=$(elem)?$(elem).attr("datetime"):$(elem).attr("title");

return$(iso8601);

},

isTime:function(elem){

//jQuery's`is()`doesn'tplaywellwithHTML5inIE

return$(elem).get(0).rCa()==="time";//$(elem).is("time");

}

});

//functionsthatcanbecalledvia$(el).timeago('action')

//initisdefaultwhennoactionisgiven

//functionsarecalledwithcontextofasingleelement

varfunctions={

init:function(){

varrefresh_el=$.proxy(refresh,this);

refresh_el();

var$s=$gs;

if($hMillis>0){

tInterval(refresh_el,$hMillis);

}

},

update:function(time){

$(this).data('timeago',{datetime:$(time)});

(this);

},

updateFromDOM:function(){

$(this).data('timeago',{datetime:$($(this)?$(this).attr("datetime"):$(this).attr("title"))});

(this);

}

};

$.o=function(action,options){

varfn=action?functions[action]:;

if(!fn){

thrownewError("Unknownfunctionname'"+action+"'fortimeago");

}

//eachoverobjectshereandcalltherequestedfunction

(function(){

(this,options);

});

returnthis;

};

functionrefresh(){

vardata=prepareData(this);

var$s=$gs;

if(!isNaN(me)){

if($==0||distance(me)<$){

$(this).text(inWords(me));

}

}

returnthis;

}

functionprepareData(element){

element=$(element);

if(!("timeago")){

("timeago",{datetime:$me(element)});

vartext=$.trim(());

if($Title){

("title",('timeago').leString());

}elif(>0&&!($(element)&&("title"))){

("title",text);

}

}

("timeago");

}

functioninWords(date){

return$s(distance(date));

}

functiondistance(date){

return(newDate().getTime()-e());

}

//fixforIE6suckage

Element("abbr");

Element("time");

}));

希望本⽂所述对⼤家的javascript程序设计有所帮助。

本文发布于:2022-11-27 15:45:15,感谢您对本站的认可!

本文链接:http://www.wtabcd.cn/fanwen/fan/90/31851.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:longlongtimeago
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图