JavaScript獲取當前時間: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" ...
JavaScript獲取當前時間:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> //返回時間格式:年-月-日 時:分:秒 function getDateString(date) { // 獲取傳入的時間,若沒有傳值則取當前時間 var dateStr = date || new Date(); // 獲取時間的年月日 var year = dateStr.getFullYear().toString().padStart(4, "0"); var month = (dateStr.getMonth() + 1).toString().padStart(2, "0"); var day = dateStr.getDate().toString().padStart(2, "0"); // 獲取時間的時分秒 var hour = dateStr.getHours().toString().padStart(2, "0"); var minute = dateStr.getMinutes().toString().padStart(2, "0"); var second = dateStr.getSeconds().toString().padStart(2, "0"); //返回時間格式:年-月-日 時:分:秒 return `${year}-${month}-${day} ${hour}:${minute}:${second}`; } console.log(getDateString()); </script> </body> </html>index.html