[Javascript] Moment.js與Day.js轉換

Moment.js
https://github.com/moment/moment/

Day.js
https://github.com/iamkun/dayjs

Moment.js 是一個大而全的Javascript時間庫,但若想要降低編譯後Javascript包的大小,或是降低通過CDN下載相關Javascript的流量,就可以考慮使用Day.js。兩者於格式化(format)、計算時間差(diff)與時間增減量(add)都可互通互換,只要更換Javascript與初始化對象即可。


以下為單html檔測試範例︰
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Moment.js & Day.js Convert Demo</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <!--使用Moment.js-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

    <!--使用Day.js-->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.10/dayjs.min.js"></script>

</head>
<body>

    <div id="app"></div>

    <script>

        function ft_mm(t) {
            //format

            let o = moment(t, 'YYYY/MM/DD HH:mm:ss')
            return o.format('YYYY/MM/DD HH:mm:ss')
        }

        function ft_dy(t) {
            //format

            let o = dayjs(t, 'YYYY/MM/DD HH:mm:ss')
            return o.format('YYYY/MM/DD HH:mm:ss')
        }

        function diff_mm(t1, t2) {
            //diff

            let o1 = moment(t1, 'YYYY/MM/DD HH:mm:ss')
            let o2 = moment(t2, 'YYYY/MM/DD HH:mm:ss')
            return o2.diff(o1, 'seconds')
        }

        function diff_dy(t1, t2) {
            //diff

            let o1 = dayjs(t1, 'YYYY/MM/DD HH:mm:ss')
            let o2 = dayjs(t2, 'YYYY/MM/DD HH:mm:ss')
            return o2.diff(o1, 'seconds')
        }

        function add_mm(t, im) {
            //add

            let o = moment(t, 'YYYY/MM/DD HH:mm:ss')
            return o.add(im, 'months').format('YYYY/MM/DD HH:mm:ss')
        }

        function add_dy(t, im) {
            //add

            let o = dayjs(t, 'YYYY/MM/DD HH:mm:ss')
            return o.add(im, 'months').format('YYYY/MM/DD HH:mm:ss')
        }

        console.log = function (c, v) {
            //覆蓋log, 使用jQuery輸出至網頁
            $('#app').append('<div style="padding:3px;">' + 'log: ' + c + ', ' + v + '</div>')
        }

        //比對format
        let t = '2019/01/02 03:04:05'
        let pt1 = ft_mm(t)
        let pt2 = ft_dy(t)
        console.log('ft_mm', pt1)
        console.log('ft_dy', pt2)
        //2019/01/02 03:04:05

        //比對diff
        let t1 = t
        let t2 = '2019/01/02 03:14:15'
        let ptfs1 = diff_mm(t1, t2)
        let ptfs2 = diff_dy(t1, t2)
        console.log('diff_mm', ptfs1)
        console.log('diff_dy', ptfs2)
        //610

        //比對add
        let im = 2
        let ptam1 = add_mm(t, im)
        let ptam2 = add_dy(t, im)
        console.log('add_mm', ptam1)
        console.log('add_dy', ptam2)
        //2019/03/02 03:04:05

    </script>

</body>
</html>


載入後畫面為︰



#Javascript, Moment.js, Day.js, time, date, 時間, 格式化, 設置, 解析, 轉換

留言