【JS】获取当前时间,且格式为yyyy-MM-dd hh:mm:ss

我们在前端获取当前时间

var nowDate = new Date();

时间格式为:

Sun May 27 2018 19:28:09 GMT+0800 (中国标准时间)

但是我们想在页面上显示为 2007-1-31 8:30的格式,所以需要对时间进行转换:

var nowDate = new Date();
 var year = nowDate.getFullYear();
 var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
  : nowDate.getMonth() + 1;
 var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate
  .getDate();
var hour = nowDate.getHours(); 
var minutes = nowDate.getMinutes();
var seconds = nowDate.getSeconds();
 var dateStr = year + "-" + month + "-" + day +" " + hour +":" +minutes+":"+seconds; 
 console.log(dateStr);


猜你喜欢

转载自blog.csdn.net/wkx18330698534/article/details/80471659