10

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

Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74

5 Answers5

14

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);
Sharanya Dutta
  • 3,981
  • 2
  • 17
  • 27
  • If you want to refine a date including the hours/minutes `"25/04/1987 14:52"` you can add `+ds.substr(10, 15)`, so something like: `dateString.substr(6, 4)+"-"+dateString.substr(3, 2)+"-"+dateString.substr(0, 2)+ds.substr(10, 15)` – Nadav Dec 20 '20 at 11:53
5

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.

freakish
  • 54,167
  • 9
  • 132
  • 169
4

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;
    }
}
Andre Figueiredo
  • 12,930
  • 8
  • 48
  • 74
0

If you are going to pass a string to the date constructor it is recommend that you use the ISO8601 format. Try this.

function createDateObject(value) {
    try {
        var parts = value.split('/');
        return new Date(parts[2] + "-" + parts[1] + "-" + parts[0]);
    } catch () {
        return null;
    }
}
Danny
  • 7,368
  • 8
  • 46
  • 70
0

You can use split to swich your items like this :

function createDateObject(value){
  var splitDate = value.split("/");
  return new Date(splitDate[2],splitDate[1],splitDate[0]);
}
Maxdow
  • 1,006
  • 11
  • 21