Swap month with day in date string in Javascript

date, javascript

Solution

Thanks to CBroe I used `Array.reverse` and it worked with my test cases.

Just replaced **swap with reverse():

function createDateObject(value) {
    try {
        return new Date(value.split('/').reverse().join('/'));
    }
    catch(e) {
        return null;
    }
}

It creates the Date correctly, but let invalid dates to be created, such as Feb/30/2014. So I also have to validate string using this Answer:

function createDateObject(value) {
    try {
        string formatted = value.split('/').reverse().join('/');
        return isValidDate(formatted) ? new Date(formatted) : null;
    } catch(e) {
        return null;
    }
}

Problem

I have a date string in format dd/MM/yyyy and I want to create a Date object from this string. `new Date(dd/MM/yyyy)` won't work.. I have this code, that obviously does not work: ``` function createDateObject(value){ try{ return new Date(value.split('/').**swap(0, 1)**.join('/')); } catch(){ return null; } } createDateObject('31/01/2014') => Fri Jan 31 2014 00:00:00 GMT-0200 (Local Daylight Time) ``` Which is the simplest way to do this? I wouldn't like to create a lot of temp variables if I could do it in one single line...

Original source