//获取当前时间,格式YYYY-MM-DD
//方法一
function nowtime() {
var date = new Date()
var seperator1 = '-'
var year = date.getFullYear()
var month = date.getMonth() + 1
var strDate = date.getDate()
if (month >= 1 && month <= 9) {
month = '0' + month
}
if (strDate >= 0 && strDate <= 9) {
strDate = '0' + strDate
}
var currentdate = year + seperator1 + month + seperator1 + strDate
return currentdate
}
//方法二
var dqrq = new Date();
var nowtime = time(dqrq.getFullYear()) + '-' + time((dqrq.getMonth() + 1)) + '-' + time(dqrq.getDate());
function time(s) {
return s < 10 ? '0' + s : s;
}
时间戳和日期互相转换在开发时经常用到,简单整理如下:
//时间戳转日期
function timestampToTime(timestamp) {
var date = new Date(timestamp * 1000);//时间戳为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() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
var h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
var m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
var s = (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());
return Y+M+D+h+m+s;
}
timestampToTime(1403058804);
日期转时间戳
function DateToUnix(string) {
var f = string.split(' ', 2);
var d = (f[0] ? f[0] : '').split('-', 3);
var t = (f[1] ? f[1] : '').split(':', 3);
return (new Date(
parseInt(d[0], 10) || null, (parseInt(d[1], 10) || 1) - 1, parseInt(d[2], 10) || null, parseInt(t[0], 10) || null, parseInt(t[1], 10) || null, parseInt(t[2], 10) || null)).getTime() / 1000;
};
时间戳倒计时
var oTime="1607592644000"; //毫秒
var oPerTime=(new Date()).getTime();
function countdown(){
var oPerTime=(new Date()).getTime();
var oT=oTime-oPerTime;
d = Math.floor(oT/1000/60/60/24);
h = Math.floor(oT/1000/60/60%24);
m = Math.floor(oT/1000/60%60);
s = Math.floor(oT/1000%60);
$('.countdown').html("<span>"+touDou(d)+"</span>天<span>"+touDou(h)+"</span>时<span>"+touDou(m)+"</span>分<span>"+touDou(s)+"</span>秒")
}
countdown();
// 补零
function touDou(n){
return n>9? n:"0"+n;
}
setInterval(countdown,1000);