All files / src/utils/Formatters DateFormatter.js

67.74% Statements 21/31
61.11% Branches 11/18
66.66% Functions 10/15
65.51% Lines 19/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61            18630x   7x             3726x 3726x               3726x 3726x 3726x 3726x     7x       7x 7x       3732x   3732x 3726x 3732x 3732x 6x   22356x                   7x      
import Formatter from './Formatter';
 
/**
 * @TODO: use moment or some other library
 */
 
const fix = (num, length = 2) => String(num).padStart(length, '0');
 
const replacers = {
    yyyy(date) {
        if (process.env.NODE_ENV === 'development') {
            console.warn('[cloud-ui] Please use YYYY instead of yyyy');
        }
        return date.getFullYear();
    },
    YYYY(date) { return date.getFullYear(); },
    MM(date) { return fix(date.getMonth() + 1); },
    dd(date) {
        if (process.env.NODE_ENV === 'development') {
            console.warn('[cloud-ui] Please use DD instead of dd');
        }
        return fix(date.getDate());
    },
    QQ(date) { return `Q${Math.ceil((date.getMonth() + 1)/3)}`},
    DD(date) { return fix(date.getDate()); },
    HH(date) { return fix(date.getHours()); },
    mm(date) { return fix(date.getMinutes()); },
    ss(date) { return fix(date.getSeconds()); },
    ms(date) { return fix(date.getMilliseconds(), 3); },
};
const trunk = new RegExp(Object.keys(replacers).join('|'), 'g');
 
export class DateFormatter extends Formatter {
    constructor(pattern = 'YYYY-MM-DD HH:mm:ss') {
        super();
        this.pattern = pattern;
    }
 
    format(value, pattern) {
        pattern = pattern || this.pattern;
 
        if (value && !isNaN(value))
            value = +value;
        const date = new Date(value);
        if (String(date) === 'Invalid Date')
            return value;
 
        return pattern.replace(trunk, (cap) => replacers[cap] ? replacers[cap](date) : '');
    }
 
    parse(value, pattern) {
        pattern = pattern || this.pattern;
 
        return new Date(value);
    }
}
 
export const dateFormatter = new DateFormatter();
 
export default DateFormatter;