Format yyymmdd date

2019-09-22 02:17发布

问题:

I need this javascript function to not split a yyyy-mm-dd but split a yyymmdd. Current date formats are 2011-11-02 but this function needs to work with 20111102.

Script:

        function evaluateEventDate(eventdate, date){
        var eventdate = eventdate.split('-');
        var date = date.split('-');

        if (eventdate[0] === 'yyyy')
        {
            eventdate[0] = date[0];
        }

        if (eventdate[1] === 'mm') 
        {
            eventdate[1] = date[1];
        }

        if (eventdate[2] === 'dd')
        {
            eventdate[2] = date[2];
        }

        return eventdate[0]+'-'+eventdate[1]+'-'+eventdate[2];
    };

回答1:

Continuing my work from your other question, I came up with the following function to solve your problem, using substr:

function evaluateEventDate(eventdate, date){
    var event_y = eventdate.substr(0, 4);
    var event_m = eventdate.substr(4, 2);
    var event_d = eventdate.substr(6, 2);

    var date = date.split('-');

    if (event_y === 'yyyy')
    {
        event_y = date[0];
    }

    if (event_m === 'mm') 
    {
        event_m = date[1];
    }

    if (event_d === 'dd')
    {
        event_d = date[2];
    }

    return event_y + '-' + event_m + '-' + event_d;
};


回答2:

You could do this:

var date = date.match(/(\d{4})(\d{2})(\d{2})/); // [yyyymmdd, yyyy, mm, dd]
date.shift(); // remove yyyymmdd from array.
...