How do I format a timestamp in Javascript to display it in graphs? UTC is fine

后端 未结 3 1261
-上瘾入骨i
-上瘾入骨i 2021-02-13 02:19

Basically, I receive raw timestamps and I need to format them into HH:MM:SS format.

3条回答
  •  盖世英雄少女心
    2021-02-13 03:01

    Here's a function that provides flexible formatting of a date in UTC. It accepts a format string similar to that of Java's SimpleDateFormat:

    function formatDate(date, fmt) {
        function pad(value) {
            return (value.toString().length < 2) ? '0' + value : value;
        }
        return fmt.replace(/%([a-zA-Z])/g, function (_, fmtCode) {
            switch (fmtCode) {
            case 'Y':
                return date.getUTCFullYear();
            case 'M':
                return pad(date.getUTCMonth() + 1);
            case 'd':
                return pad(date.getUTCDate());
            case 'H':
                return pad(date.getUTCHours());
            case 'm':
                return pad(date.getUTCMinutes());
            case 's':
                return pad(date.getUTCSeconds());
            default:
                throw new Error('Unsupported format code: ' + fmtCode);
            }
        });
    }
    

    You could use it like this:

    formatDate(new Date(timestamp), '%H:%m:%s');
    

提交回复
热议问题