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

const now = new Date();
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const date = now.getDate().toString().padStart(2, '0');
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
const weekdays = [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
const week = weekdays[now.getDay()];  //星期
const time = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}` //年月日 时分秒
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
JavaScript 中,获取当前日期和时间通常使用内置的 `Date` 对象。要获取当前的年、月、日、时、分和秒,你可以使用以下几个方法: ```javascript // 创建一个新的 Date 对象,代表当前时间 const now = new Date(); // 获取年份 const year = now.getFullYear(); // 例如:2023 // 获取月份(注意:月份是从0开始计数的,0表示 January) const month = now.getMonth() + 1; // 加1是因为月份从1开始,例如:12(December) // 获取日期 const date = now.getDate(); // 例如:31 // 获取小时(24小时制) const hours = now.getHours(); // 例如:14 // 获取分钟 const minutes = now.getMinutes(); // 例如:30 // 获取秒 const seconds = now.getSeconds(); // 例如:45 // 如果需要完整的时间字符串,可以组合这些部分 const fullTime = `${year}-${month < 10 ? '0' : ''}${month}-${date < 10 ? '0' : ''}${date} ${hours < 10 ? '0' : ''}${hours}:${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}`; console.log(fullTime); // 输出:2023-12-31 14:30:45 ``` 如果你想得到特定格式的字符串,可以使用 `toLocaleString()` 方法,例如: ```javascript const formattedDateTime = now.toLocaleString('default', { hour: '2-digit', minute: '2-digit', second: '2-digit' }); console.log(formattedDateTime); // 输出:12:30:45 PM ``` 如果你需要每小时、每天或每周的日期,可以结合 `setHours()`、`setMinutes()` 和 `setSeconds()` 方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Y2000104

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值