Convert a date to Java

Asked

Viewed 652 times

3

Good Afternoon. How do I convert a date into Java, taking into account the date entered may be 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 entered the date with formats 01-10-2015 or 01/10/2015.

What solutions do I have? Thank you.

  • I advise you to have only one type of input mask. Is there a specific reason for having two input masks?

  • Will the year always have 4 characters? For example: 1998 instead of 98? In addition, in the question the format is "year-day-month", which means that the date of example there is "10 January 2015". That’s right?

2 answers

3

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

A 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: http://jsfiddle.net/Sergio_fiddle/xqzssh8u/

  • 2

    Yes. Working with date requires knowledge of what you really need. Very good your answer is somewhat more complete.

2


Make sure below is enough for you. If you still have doubts, 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);

  • 1

    It worked as I wanted. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.