Convert a date to javaScript

3
Good afternoon. How do I convert a date to javaScript, taking into account the entered date can be format day-month-year or year-day-month. I have the following code:

data = toDate('2015-10-01');

function toDate(dateStr) {
            dateStr = dateStr.replace('/', '-');
            var parts = dateStr.split("-");
            return new Date(parts[2], parts[1] - 1, parts[0]);
        }

But the function does not solve the problem if I inserted the date with the formats 01-10-2015 or 01/10/2015.

What solutions do I have? Thank you.

    
asked by anonymous 14.12.2015 / 16:43

2 answers

2

Make sure below is enough for you. If you still have questions, comment.

var st = "26-04-2013";
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));

alert(dt);
    
14.12.2015 / 17:01
3

If you want a function that works with day-month-year or year-day-month you have to detect which format it is.

One suggestion:

function datar(str) {
    var partes = str.split(/[\/\-]/);
    var date = partes[0].length == 4 ? new Date(partes[0], partes[2], partes[1]) : new Date(partes[2], partes[1], partes[0]);
    return date;
}

console.log(datar('01-10-2015')); // Sun Nov 01 2015 00:00:00 GMT+0100 (W. Europe Standard Time)
console.log(datar('2015/20/10')); // Fri Nov 20 2015 00:00:00 GMT+0100 (W. Europe Standard Time)

jsFiddle: link

    
14.12.2015 / 18:54