1. 程式人生 > >jq 時間計算

jq 時間計算

color extend rdate console 小時 int class time repl

-(function($){
        var caculation = function(gap){
            var minutes = 1000 * 60
            var hours = minutes * 60
            var days = hours * 24
            var years = days * 365
            if(gap/years >= 1){
                return parseInt(gap/years)+‘年‘;
            }else
if(gap/days >= 30){ return parseInt(gap/days/30)+‘個月‘ }else if(gap/hours >= 24){ return parseInt(gap/hours/24)+‘天‘ }else if(gap/minutes >=60){ var num = gap/minutes/60; var intNum = parseInt(gap/minutes/60);
return intNum+‘小時‘+parseInt((num.toFixed(4)-intNum)*60)+‘分鐘‘ }else{ return parseInt(gap/minutes)+‘分鐘‘ } } $.extend({ nowToTime:function(time){ var theTime = Date.parse(time .replace(/-/g,"/")); var
curDate=new Date().valueOf();//當前時間的時間戳 var gap = theTime - curDate return theTime <=curDate? alert("請選擇大於今天的時間!"): caculation(gap); }, timeToNow:function(time){ var theTime = Date.parse(time .replace(/-/g,"/")); var curDate=new Date().valueOf(); var gap = curDate - theTime; return theTime <=curDate? caculation(gap): alert("請選擇小於今天的時間!"); } }) })(jQuery);

使用:

console.log($.nowToTime(‘2017-7-16 17:51:34‘)+‘後‘);
console.log($.timeToNow(‘2017-07-15 18:01:23‘)+‘前‘);

結果:

23小時36分鐘後
13分鐘前

jq 時間計算