美文网首页
JavaScript 日期、日期格式化、时间计时器

JavaScript 日期、日期格式化、时间计时器

作者: 暴躁程序员 | 来源:发表于2022-03-24 14:37 被阅读0次

1. 日期对象的几种常见参数

new Date() // 当前时间对象
new Date(十三位时间戳)
new Date(年, 月, 日, 时, 分, 秒, 毫秒)
new Date('年-月-日 时:分:秒:毫秒')

console.log(new Date().getTime());
console.log(new Date(1643689230011).getTime());
console.log(new Date(2022, 01, 01, 12, 20, 30, 11).getTime());
console.log(new Date('2022-01-01 12:20:30:11').getTime());

2. 获取日期信息的常用方法

console.log(new Date().getTime());         // 获取13位时间戳 或者 从 1970 年 1 月 1 日至今的毫秒数
console.log(new Date().getFullYear());     // 年
console.log(new Date().getMonth());        // 月   0 ~ 11
console.log(new Date().getDate());         // 日
console.log(new Date().getHours());        // 时
console.log(new Date().getMinutes());      // 分
console.log(new Date().getSeconds());      // 秒
console.log(new Date().getMilliseconds()); // 毫秒
console.log(new Date().getDay());          // 周   0 ~ 6

3. 时间格式化

方式一

window.Date.prototype.format = function (fmt) {
    var dict = {
        "M+": this.getMonth() + 1,                       // 月
        "D+": this.getDate(),                            // 日
        "h+": this.getHours(),                           // 时
        "m+": this.getMinutes(),                         // 分
        "s+": this.getSeconds(),                         // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3),     // 季度
        "ms": this.getMilliseconds()                     // 毫秒
    };
    if (/(Y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var d in dict) {
        if (new RegExp("(" + d + ")").test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (dict[d]) : (("00" + dict[d]).substr(("" + dict[d]).length)));
        }
    }
    return fmt;
}
document.getElementById("timer").innerText = new Date(1648029253539).format("YYYY-MM-DD hh:mm:ss q ms");

方式二

document.getElementById("timer").innerText = formatDate(new Date(), 'YYYY-MM-DD hh:mm:ss');
function formatDate(date, fmt) {
  let eve;
  const dict = {
    "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 d in dict) {
    eve = new RegExp("(" + d + ")").exec(fmt);
    if (eve) {
      fmt = fmt.replace(eve[1], (eve[1].length == 1) ? (dict[d]) : (dict[d].padStart(eve[1].length, "0")))
    };
  };
  return fmt;
}

4. 时间计时器

倒计时

let last_seconds = 60 + 10 // 最终秒数
const timer = setInterval("countDownTime()", 1000);
function countDownTime() {
  if (last_seconds >= 0) {
    const days = parseInt(last_seconds / 60 / 60 / 24, 10);      //剩余的天数
    const hours = parseInt(last_seconds / 60 / 60 % 24, 10);     //剩余的小时
    const minutes = parseInt(last_seconds / 60 % 60, 10);        //剩余的分钟
    const seconds = parseInt(last_seconds % 60, 10);             //剩余的秒数
    const showContent = `距离倒计时结束还有${formate0to9(days)}天${formate0to9(hours)}时${formate0to9(minutes)}分${formate0to9(seconds)}秒`
    document.getElementById("timer").innerText = showContent;
    --last_seconds
  } else {
    clearInterval(timer);
    document.getElementById("timer").innerText = `倒计时结束`;

  }
}

// 小于10 加0 处理
function formate0to9(arg) {
  if (arg < 10) {
    return '0' + arg
  } else {
    return arg
  }
}

正计时

// 正计时 10s 后停止
let last_seconds = 0 // 起始
const length = 10 // 即时秒数
const timer = setInterval("countUpTime()", 1000);
function countUpTime() {
  if (last_seconds <= length) {
    const showContent = `已进行${last_seconds}秒`
    document.getElementById("timer").innerText = showContent;
    ++last_seconds
  } else {
    clearInterval(timer);
    document.getElementById("timer").innerText = `结束`;
  }
}

相关文章

网友评论

      本文标题:JavaScript 日期、日期格式化、时间计时器

      本文链接:https://www.haomeiwen.com/subject/xwnkjrtx.html