JS获取当前时间转成时间戳,并比较两个时间戳得出相差的天数
获取当前时间,转为时间戳比较大小,得出它的天数
/** *获取当前时间 *format=1精确到天 *format=2精确到分 */ function getCurrentDate(format) { var now = new Date(); var year = now.getFullYear(); //得到年份 var month = now.getMonth();//得到月份 var date = now.getDate();//得到日期 var day = now.getDay();//得到周几 var hour = now.getHours();//得到小时 var minu = now.getMinutes();//得到分钟 var sec = now.getSeconds();//得到秒 month = month + 1; if (month < 10) month = "0" + month; if (date < 10) date = "0" + date; if (hour < 10) hour = "0" + hour; if (minu < 10) minu = "0" + minu; if (sec < 10) sec = "0" + sec; var time = ""; //精确到天 if(format==1){ time = year + "-" + month + "-" + date; } //精确到分 else if(format==2){ time = year + "-" + month + "-" + date+ " " + hour + ":" + minu + ":" + sec; } return time; }//格式:2020-06-22 22:43:24
//比较大小,得出它的天数 function follow_status(value){ var that_time = Date.parse(getCurrentDate(2));//获取当前时间,并转成时间戳 var updata_time = Date.parse(value);//你输入的时间,格式:2020-06-20 18:31:30 //两者相差的天数 var num_day = (that_time-updata_time)/(1000*60*60*24); return num_day };
将时间戳转换成正常时间
function timestampToTime(timestamp) { var date = "" if(timestamp.length == 13) { date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000 } else { date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000 } var Y = date.getFullYear() + '-'; var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; var D = date.getDate() + ' '; var h = date.getHours() + ':'; var m = date.getMinutes() + ':'; var s = date.getSeconds(); return Y + M + D + h + m + s; } var date_time = Date.parse("2020-06-20 18:31:30");//转为时间戳 console.log(timestampToTime(date_time));//2020-06-20 18:31:30
JS获取当前时间戳的方法:https://www.cnblogs.com/deepalley/p/10486714.html