前端用js寫一個函數輸出當前時間,格式為yyyy-mm-dd hh:mm:ss


  • 需求描述:寫一個函數輸出當前時間,格式為yyyy-mm-dd hh:mm:ss
  • 實現思路:
    • 方法一:首先獲取當天時間,然后調用toLocaleString方法,將當天時間轉換為字符串。再用replace方法將其替換成想要的格式。
    • 方法二:首先獲取當前時間,然后使用getFullYear、getMonth、getDate、getHours、getMinutes、getSeconds方法,分別獲取年月日時分秒,再按照需要的格式將其拼接成字符串
  • 實現代碼:

方法一:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>按指定格式輸出當前日期和時間</title>
</head>
<body>
<script type="text/javascript">
    function getDate() {
        let today = new Date();
        // console.log(today):  Wed Jul 17 2019 17:48:53 GMT+0800 (中國標准時間)
        let date = today.toLocaleString().replace(/下午/, " ");
        // console.log(today.toLocaleString()):  2019/7/17 下午5:48:53 
        return date;
    }
    document.write(getDate());
    // date: 2019/7/17 5:48:53
</script>
</body>
</html>

 

方法二:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>按指定格式輸出當前日期和時間</title>
</head>
<body>
<script type="text/javascript">
    function getDate() {
        let today = new Date();
        // console.log(today):  Wed Jul 17 2019 17:48:53 GMT+0800 (中國標准時間)
        let newDate = today.getFullYear() + '/' + (today.getMonth() + 1) + '/' + today.getDate() + ' ' + today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
        // getMonth方法返回的是0-11之間的數字,代表1-12月份,若想和日歷的月份時間對應,需要+1。
        return newDate;
    }
    document.write(getDate());
</script>

</body>
</html>
  •  效果圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM