前端用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>
  •  效果图:

猜你喜欢

转载自www.cnblogs.com/caoxueying2018/p/11202935.html