【JS】日期时间格式化

gengboxb 900 0

时间格式化yyyy-MM-dd HH:mm:ss 与 yyyy-MM-dd

获取当前时间函数

function mounthShort() {
  return new Date();
};

时间格式化函数

function dateFormate(dateTime, timeflag) {
    const date = new Date(Date.parse(dateTime));
    const y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? (`0${m}`) : m;
    let d = date.getDate();
    d = d < 10 ? (`0${d}`) : d;
    let h = date.getHours();
    h = h < 10 ? (`0${h}`) : h;
    let minute = date.getMinutes();
    minute = minute < 10 ? (`0${minute}`) : minute;
    let seconds = date.getSeconds();
    seconds = seconds < 10 ? (`0${seconds}`) : seconds;
    let result = '';
    if (timeflag) {
      result = `${y}-${m}-${d} ${h}:${minute}:${seconds}`;
    } else {
      result = `${y}-${m}-${d}`;
    }
    return result;
  };

调用并格式化

var time = mounthShort(); // 返回的值 Wed May 08 2019 09:46:57 GMT+0800 (中国标准时间)
var timeFormat = dateFormate(time,true); // 格式 yyyy-MM-dd HH:mm:ss
var timeFormats = dateFormate(time,false); // 格式 yyyy-MM-dd
console.log(timeFormat); // 2019-05-08 09:46:57
console.log(timeFormats); // 2019-05-08

完整代码

function mounthShort() {
  return new Date();
};
​
function dateFormate(dateTime, timeflag) {
    const date = new Date(Date.parse(dateTime));
    const y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? (`0${m}`) : m;
    let d = date.getDate();
    d = d < 10 ? (`0${d}`) : d;
    let h = date.getHours();
    h = h < 10 ? (`0${h}`) : h;
    let minute = date.getMinutes();
    minute = minute < 10 ? (`0${minute}`) : minute;
    let seconds = date.getSeconds();
    seconds = seconds < 10 ? (`0${seconds}`) : seconds;
    let result = '';
    if (timeflag) {
      result = `${y}-${m}-${d} ${h}:${minute}:${seconds}`;
    } else {
      result = `${y}-${m}-${d}`;
    }
    return result;
  };
​
var time = mounthShort(); // 返回的值 Wed May 08 2019 09:46:57 GMT+0800 (中国标准时间)
var timeFormat = dateFormate(time,true); // 格式 yyyy-MM-dd HH:mm:ss
var timeFormats = dateFormate(time,false); // 格式 yyyy-MM-dd
console.log(timeFormat); // 2019-05-08 09:46:57
console.log(timeFormats); // 2019-05-08

发表评论 取消回复
表情 图片 链接 代码

分享