js 获取当前日期时间 格式为 yyyy-mm-dd hh MM ss

博主分享了其老师关于人工智能的教程,适合零基础学习者,内容通俗易懂,旨在普及AI知识,促进民族复兴。

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.youkuaiyun.com/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>

<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
function curDateTime(){
var d = new Date();
var year = d.getYear();
var month = d.getMonth()+1;
var date = d.getDate();
var day = d.getDay();
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
var ms = d.getMilliseconds();  
var curDateTime= year;
if(month>9)
 curDateTime = curDateTime +"-"+month;
else
 curDateTime = curDateTime +"-0"+month;
if(date>9)
 curDateTime = curDateTime +"-"+date;
else
 curDateTime = curDateTime +"-0"+date;
if(hours>9)
 curDateTime = curDateTime +" "+hours;
else
 curDateTime = curDateTime +" 0"+hours;
if(minutes>9)
 curDateTime = curDateTime +":"+minutes;
else
 curDateTime = curDateTime +":0"+minutes;
if(seconds>9)
 curDateTime = curDateTime +":"+seconds;
else
 curDateTime = curDateTime +":0"+seconds;
return curDateTime;
}
 
alert(curDateTime());
 
//-->
</SCRIPT>
</BODY>
</HTML>

           

给我老师的人工智能教程打call!http://blog.youkuaiyun.com/jiangjunshow
这里写图片描述
在 JavaScript 中,你可以使用 `Date` 对象来获取当前时间,并通过方法提取年、月、日、时、分、秒等信息。以下是一个将当前时间格式化为 `yyyy-mm-dd hh-mm-ss` 格式的函数: ```javascript function getCurrentTimeFormatted() { const now = new Date(); const year = now.getFullYear(); // 获取年份 (yyyy) const month = String(now.getMonth() + 1).padStart(2, '0'); // 获取月份 (mm),注意月份从0开始 const day = String(now.getDate()).padStart(2, '0'); // 获取日期 (dd) const hours = String(now.getHours()).padStart(2, '0'); // 获取小时 (hh) const minutes = String(now.getMinutes()).padStart(2, '0'); // 获取分钟 (mm) const seconds = String(now.getSeconds()).padStart(2, '0'); // 获取秒数 (ss) // 拼接格式yyyy-mm-dd hh-mm-ss return `${year}-${month}-${day} ${hours}-${minutes}-${seconds}`; } // 调用函数获取格式化后的时间 console.log(getCurrentTimeFormatted()); ``` ### 代码解释: 1. `new Date()` 创建一个表示当前时间的 `Date` 对象。 2. `getFullYear()`:获取四位数的年份。 3. `getMonth() + 1`:获取月份,`getMonth()` 返回的是 0 到 11,分别表示 1 月到 12 月,所以需要 1。 4. `getDate()`:获取日期。 5. `getHours()`、`getMinutes()`、`getSeconds()`:分别获取小时、分钟、秒。 6. `String().padStart(2, '0')`:将数字转换为字符串,并在不足两位时前面补 0,确保格式为两位数。 7. 使用模板字符串拼接最终格式为 `yyyy-mm-dd hh-mm-ss`。 ### 示例输出: ``` 2025-04-05 14-30-45 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值