获取当前日期时间 年月日 时分秒

  getCurrentTime() {
      let date = new Date()
      let Y = date.getFullYear(); //获取系统的年;
      let M = date.getMonth() + 1; //获取系统月份,由于月份是从0开始计算,所以要加1
      let D = date.getDate(); //获取系统日
      let H = date.getHours(); //获取系统时间
      let m = date.getMinutes() > 10 ? date.getMinutes() : '0' + date.getMinutes(); //分
      let s = date.getSeconds(); //秒
      M = M < 10 ? '0' + M : M
      D = D < 10 ? '0' + D : D
      H = H < 10 ? '0' + H : H
      s = s < 10 ? '0' + s : s
      return Y + '-' + M + '-' + D + ' ' + H + ':' + m + ':' + s
      // return Y + '年' + M + '月' + D + '日' + h + '时' + m + '分'
    }
### JavaScript 获取当前日期时间年月日时分秒 以下是通过 JavaScript 实现获取当前时间的年、月、日、小时、分钟和秒钟的一个完整示例: ```javascript function getCurrentDateTime() { const now = new Date(); // 创建一个新的Date对象表示当前时间[^2] const year = now.getFullYear(); // 获取完整的四位数年份 const month = String(now.getMonth() + 1).padStart(2, '0'); // 获取月份 (注意:getMonth返回的是0-11)[^3] const day = String(now.getDate()).padStart(2, '0'); // 获取一个月中的某一天 (1-31) const hours = String(now.getHours()).padStart(2, '0'); // 获取小时 (0-23) const minutes = String(now.getMinutes()).padStart(2, '0'); // 获取分钟 (0-59) const seconds = String(now.getSeconds()).padStart(2, '0'); // 获取秒钟 (0-59) return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; // 返回格式化后的日期时间字符串 } console.log(getCurrentDateTime()); ``` 上述代码实现了以下功能: - 使用 `new Date()` 方法创建了一个新的时间对象来代表当前时刻。 - 调用了多个 `Date` 对象的方法分别提取年 (`getFullYear`)、月 (`getMonth`)、日 (`getDate`)、小时 (`getHours`)、分钟 (`getMinutes`) 和秒 (`getSeconds`) 的值。 - 利用 `String.prototype.padStart` 方法确保月份、日期、小时、分钟和秒始终以两位数字的形式展示。 此函数调用后会在控制台打印出形如 `YYYY-MM-DD HH:mm:ss` 的当前时间字符串。 ### 注意事项 如果需要将该时间用于表单输入或其他 HTML 元素绑定,可以考虑结合 jQuery EasyUI 或其他前端框架的功能进一步扩展。例如,在某些场景下可以直接设置 `easyui-datebox` 的初始值为当前时间[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值