js 获取当前时间特定格式

1.获取当前时间

let newDate = new Date(); // 当前日期和时间的 Date 对象

2.获取时间中的年月日时分秒

    let now = new Date();
    let year = now.getFullYear();            // 获取完整的年份(4位,1970-????)
                                             // 不推荐getYear(),因为它返回的是从1900年开始计算的年份,这可能导致混淆和错误。例如,如果年份是2023年,getYear()会返回123而不是2023。

    let month = now.getMonth() + 1;          // 注意:getMonth() 返回的月份是从0开始的
    let date = now.getDate();                // 获取当前日(1-31)
    let week = now.getDay();                 // 获取当前星期X(0-6,0代表星期天)
    let hours = now.getHours();              // 获取当前小时数(0-23)
    let minutes = now.getMinutes();          // 获取当前分钟数(0-59)
    let seconds = now.getSeconds();          // 获取当前秒数(0-59)
    let millisecond = now.getMilliseconds(); // 获取当前毫秒数(0-999)
    let timestamp = now.getTime();           // 时间戳(输出一个数字,表示从1970年1月1日 00:00:00 UTC以来的毫秒数)

    // now.toLocaleDateString();             // 获取当前日期
    // now.toLocaleTimeString();             // 获取当前时间
    // now.toLocaleString();                 // 获取日期与时间

    console.log(year, month, date, week, hours, minutes, seconds, millisecond);

3.时间的格式化

/**
 * 对Date的扩展,将 Date 转化为指定格式的String
 * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符
 * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 * 例子:(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2022-02-22 08:08:08.423
 *       (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2020-2-2 2:2:2.18
 **/

Date.prototype.Format = function (fmt) {
  // author: meizz
  var o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "h+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  return fmt;
};
4.yyyy-MM-dd hh:mm:ss

yyyy-MM-dd hh:mm:ss 是一个常用于表示日期和时间的格式,但它有一个小问题:它混合了12小时制和24小时制的表示。

yyyy 表示四位数的年份,例如 2022。
MM 表示两位数的月份,例如 07 表示7月。
dd 表示两位数的日期,例如 17 表示17日。
hh 在这里可能是意图表示小时,但通常 hh 用于12小时制(即 01 到 12),而 HH 用于24小时制(即 00 到 23)。
mm 表示分钟,两位数,从 00 到 59。
ss 表示秒,两位数,从 00 到 59。

调用:


let time1 = new Date().Format("yyyy-MM-dd");
let time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");// HH 24小时制 ,hh 12小时制
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值