JS 日期時間的格式化

功能

將日期時間轉換爲指定格式,如:YYYY-mm-dd HH:MM 表示 2021-11-02 15:00

方法

/**
 * 日期格式轉換
 * @param millisecond 毫秒
 * @param template 模板(可選)
 * @example formatDate(new Date(), "YYYY-mm-dd HH:MM:SS") => 2021-11-02 09:39:59
 */
function formatDate(millisecond, template) {
  var res = "";
  try {
    var date = new Date(millisecond);
    var 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(), // 秒
    };
    template = template || "YYYY-mm-dd";
    for (var k in opt) {
      var ret = new RegExp("(" + k + ")").exec(template);
      if (ret) {
        template = template.replace(
          ret[1],
          ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
        );
      }
    }
    res = template;
  } catch (error) {
    console.warn("ERROR formatDate", error);
  }
  return res;
}

使用

formatDate(new Date(), "YYYY-mm-dd HH:MM:SS")  // 2021-11-02 09:39:59
formatDate(1635817199000) // 2021-11-02
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章