zoukankan      html  css  js  c++  java
  • 前端用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>
    •  效果图:

    致力于前端技术学习与分享,会及时更新博客。
  • 相关阅读:
    json的序列化 与 反序列化
    苹果审核被拒 2.3.10
    iOS基础问答面试
    论坛类应用双Tableview翻页效果实现
    iOS性能调优之Analyze静态分析
    win10 U盘安装ubuntu16.04双系统
    spring boot实战读书笔记1
    使用springBoot搭建REATFul风格的web demo
    es6编写generator报错
    vue开发环境搭建win10
  • 原文地址:https://www.cnblogs.com/caoxueying2018/p/11202935.html
Copyright © 2011-2022 走看看