Idea analysis
Let's first explain the final effect we need to achieve: convert the timestamp to the time format we want, for example: 2020-02-02 20:20:20, 2020-02-02... For details: https:
// timor419 .github.io/2020/03/28/JS-timestampToDate/
The following are some time format conversions and time acquisition:
const myDate = new Date(); // 获取当前时间
myDate.getYear(); //获取当前年份(2位)
myDate.getFullYear(); //获取完整的年份(4位,1970-????)
myDate.getMonth(); //获取当前月份(0-11,0代表1月) // 所以获取当前月份是myDate.getMonth()+1;
myDate.getDate(); //获取当前日(1-31)
myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
myDate.getHours(); //获取当前小时数(0-23)
myDate.getMinutes(); //获取当前分钟数(0-59)
myDate.getSeconds(); //获取当前秒数(0-59)
myDate.getMilliseconds(); //获取当前毫秒数(0-999)
myDate.toLocaleDateString(); //获取当前日期
const mytime=myDate.toLocaleTimeString(); //获取当前时间
myDate.toLocaleString( ); //获取日期与时间
Let's look directly at the code below:
1. JS-wrapper
formatDate(num, format) {
const formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
const returnArr = [];
const date = new Date(num);
returnArr.push(date.getFullYear()); // 取得4位数的年份
returnArr.push(this.formatNumber(date.getMonth() + 1)); // 取得日期中的月份,其中0表示1月,11表示12月
returnArr.push(this.formatNumber(date.getDate())); // 返回日期月份中的天数(1到31)
returnArr.push(this.formatNumber(date.getHours())); // 返回日期中的小时数(0到23)
returnArr.push(this.formatNumber(date.getMinutes())); // 返回日期中的分钟数(0到59)
returnArr.push(this.formatNumber(date.getSeconds())); // 返回日期中的秒数(0到59)
for (const i in returnArr) {
// 判断对象是否含有某个非继承属性
if ({
}.hasOwnProperty.call(returnArr, i)) {
format = format.replace(formateArr[i], returnArr[i]); // 替换
}
}
return format;
},
formatNumber(n) {
n = n.toString();
return n[1] ? n : `0${
n}`;
},
2. JS-call
// 时间戳转换为日期
getFormatDate() {
const val = 1580646020000;
console.log(this.formatDate(val, 'Y-M-D h:m:s')); // 打印值为:2020-02-02 20:20:20
console.log(this.formatDate(val, 'Y-M-D')); // 打印值为:2020-02-02
console.log(this.formatDate(val, 'Y.M.D')); // 打印值为:2020.02.02
},
------------- The End -------------
License Agreement: For reprinting, please keep the original link and author.