怎样用CDN加载和使用moment.js时区库做Javascript的时区转换?

旧金山湾区时间与北京时间转换,用Javascript方便地实现时区转换例子一文中示范了怎样用moment.js做时间的时区转换的例子。例子里下载了moment.js和moment-timezone-with-data.js,如官方文档所说的,加载如下

<script src="moment.js"></script>
<script src="moment-timezone-with-data.js"></script>

那么能不能不下载,直接用CDN呢?也是可以的

<script type="text/javascript" src="https://momentjs.com/downloads/moment.js">
</script>

<script type="text/javascript" src="https://momentjs.com/downloads/moment-timezone-with-data.js">
</script>

那么之前的例子就变成如下

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="https://momentjs.com/downloads/moment.js">
        </script>

        <script type="text/javascript" src="https://momentjs.com/downloads/moment-timezone-with-data.js">
        </script>
    </head>

    <body>
        <script>
            const sftime = moment().tz('America/Los_Angeles');
            const bjtime = moment(sftime).tz('Asia/Shanghai');

            // check result
            const fmt = 'hh:mm:ss a z YYYY-MM-DD';
            console.log(sftime.format(fmt));
            console.log(bjtime.format(fmt));
        </script>
    </body>
</html>

使用CDN就不再需要把两个js文件下载和html文件放一起,而加载地址改成CDN的URL。使用上和原来一样。

Leave a Comment

Your email address will not be published.