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

转载地址:http://www.cnblogs.com/wdw31210/archive/2012/06/27/2565865.html

$("#aa").click(function () {
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;
alert(currentTime);
});


  • 0
    点赞
  • 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值