js获取时间(年月日时分秒)

function tick() {
        var date = new Date();
        this.year = date.getFullYear();
        this.month = date.getMonth() + 1;
        this.date = date.getDate();
        this.day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[date.getDay()];
        this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        var currentTime =  this.year + "年" + this.month + "月" + this.date + "日 " + this.hour + "时" + this.minute + "分" + this.second + "秒 " + this.day;

        $("#tick").html(currentTime);
        setTimeout(tick, 1000);   
    }

 

 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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
发出的红包

打赏作者

江湖行骗老中医

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

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

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

打赏作者

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

抵扣说明:

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

余额充值