本次分享一下如何将new Date()转化为本地标准时间(eg:2019-01-07 16:51:59)。不多说,撸代码。
function time (val) {
// 初始化,如果没有传时间,则转化当前时间。
var date = val ? new Date(val) : new Date();
// 获取年
var Y = date.getFullYear();
// 分别获取月,日,时,分,秒,且如果小于10,则自动补充"0"字符串。
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;
}
好了,本次分享就这些了,如果有问题,欢迎指正,谢谢。