Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap month with day in date string in Javascript

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...

like image 602
Andre Figueiredo Avatar asked Jan 30 '14 13:01

Andre Figueiredo


3 Answers

Since your question is how to swap month with day in a string (dd/mm/yyyy to mm/dd/yyyy), this is the answer:

var dateString = "25/04/1987";
dateString = dateString.substr(3, 2)+"/"+dateString.substr(0, 2)+"/"+dateString.substr(6, 4);

However, if you would like to create a new Date() object, you have to change the string according to the ISO 8601 format (dd/mm/yyyy to yyyy-mm-dd):

var dateString = "25/04/1987";
dateString = dateString.substr(6, 4)+"-"+dateString.substr(3, 2)+"-"+dateString.substr(0, 2);
var date = new Date(dateString);
like image 152
Sharanya Dutta Avatar answered Nov 12 '22 15:11

Sharanya Dutta


How about this?

value = value.split("/");
var d = new Date(value[2], parseInt(value[1], 10)-1, value[0]);

You have to subtract 1 from month because JavaScript counts months from 0.

like image 29
freakish Avatar answered Nov 12 '22 15:11

freakish


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;
    }
}
like image 4
Andre Figueiredo Avatar answered Nov 12 '22 16:11

Andre Figueiredo