整理些好用的工具函数(一)
时间相关函数
- 时间格式化
function createDateAndTime(timeStamp) {
let date = new Date(timeStamp);
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let dateT = date.getFullYear() + '/' + (month < 10 ? ('0' + month) : month) + '/' + (day < 10 ? ('0' + day) : day) + '';
let time = (hour < 10 ? ('0' + hour) : hour) + ':' + (minute < 10 ? ('0' + minute) : minute);
return {date: dateT, time: time, day: day, month: month};
}
function dateFormat(time = new Date(),fmt = 'YYYY/MM/DD') {
let ret;
let date = new Date(time);
const opt = {
"Y+": date.getFullYear().toString(), // 年
"M+": (date.getMonth() + 1).toString(), // 月
"D+": date.getDate().toString(), // 日
"H+": date.getHours().toString(), // 时
"m+": date.getMinutes().toString(), // 分
"s+": date.getSeconds().toString() // 秒
};
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
};
};
return fmt;
}
- 某天的开始时间戳
function getDateStart(time = new Date()){
return new Date(new Date(time).toLocaleDateString()).getTime();
}
- 某天的结束时间戳
function getDateEnd(time = new Date()){
return new Date(new Date(time).toLocaleDateString()).getTime() + 24*3600*1000 - 1;
}
- 字符串长度补全(防止不支持String 的 padStart方法)
if( typeof String.prototype.padStart !== 'function'){
String.prototype.padStart = function(targetLength,padString){
let string = this
while (string.length < targetLength) {
string = padString + string
}
return string
}
}
未完待续