get date from string js code example

Example 1: js string to date

var myDate = new Date("2013/1/16");

var str = "2013/1/16";
var strToDate = new Date(str);

Example 2: how to validate from and to date using date.parse in javascript

var stringval = '01/03/2012';
var testdate;

try {
  testdate = $.datepicker.parseDate('mm/dd/yy', stringval);
             // Notice 'yy' indicates a 4-digit year value
} catch (e)
{
 alert(stringval + ' is not valid.  Format must be MM/DD/YYYY ' +
       'and the date value must be valid for the calendar.';
}

Example 3: string date to date in javascript

var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works

var invalidDate = new Date('1471793029764'); // does not work. Invalid Date

Example 4: javascript extract date from string

function getDate(d)
{
    var day, month, year;

    result = d.match("[0-9]{2}([\-/ \.])[0-9]{2}[\-/ \.][0-9]{4}");
    if(null != result) {
        dateSplitted = result[0].split(result[1]);
        day = dateSplitted[0];
        month = dateSplitted[1];
        year = dateSplitted[2];
    }
    result = d.match("[0-9]{4}([\-/ \.])[0-9]{2}[\-/ \.][0-9]{2}");
    if(null != result) {
        dateSplitted = result[0].split(result[1]);
        day = dateSplitted[2];
        month = dateSplitted[1];
        year = dateSplitted[0];
    }

    if(month>12) {
        aux = day;
        day = month;
        month = aux;
    }

    return year+"/"+month+"/"+day;
}

Tags:

Java Example