Native js time formatting method encapsulation

Native js time formatting method encapsulation

Create the formatDate function, pass in the date (time) and format (format) parameters, and simply judge the format to return the time in the corresponding format

Note: The month obtained by the getMonth() method will be 1 less than the actual month, so you need to add 1

function formatDate(date, format) {
    let yFull = date.getFullYear();
    let y = date.getYear();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    let time = '';
    if (format == 'YY/MM/DD') {
        time = y + '/' + m + '/' + d;
    } else if (format == 'YYYY/MM/DD') {
        time = yFull + '/' + m + '/' + d;
    } else if (format == 'YY-MM-DD') {
        time = y + '-' + m + '-' + d;
    } else if (format == 'YYYY-MM-DD') {
        time = yFull + '-' + m + '-' + d;
    } else {
        time = yFull + '-' + m + '-' + d;
    }
    return time
}

use:

checkDate(date) {
      console.log(this.Common.formatDate(date, 'YYYY-MM-DD'));
}

If it is helpful to you, remember to like it (~~)

Guess you like

Origin blog.csdn.net/start_sea/article/details/122200462