Convert string to JQuery

I have the string '28 -Dec-14 'in a variable. I need to convert this string to date format. my code

<body>
<input type="text" id="from" readonly="" />
<input type="text" id="to" readonly="" onchange="checkDate(this);"/>
</body>

      

here is the date selected by uidatepicker

my script -

function checkDate(obj)
{
var from = $('#from').val();
var to = obj.value;
alert(to);
var date = to.split("-")[0],
          month = to.split("-")[1],
          year = to.split("-")[2];
var d = new Date (year,month,date );
alert(d);
}

      

here year=14,month=Dec,and date=28

+3


source to share


4 answers


You can do it



var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var d = new Date (year,months[month],date );

      

0


source


No need to reinvent the wheel



 var date = new Date('28-Dec-14')

      

0


source


You can use the javascript date constructor to achieve this, just pass a date string to it;

new Date(yourString);

      

I changed part of your code assuming you are using JQuery, here is a working demo:

See the violin

0


source


it looks like you are trying to check the range and it will be pretty easy, I'll just use momentjs ( http://momentjs.com/ ) Something like this - the fiddle has more real details. Better yet, if you are using jquery ui, it already has a date range applied after: http://jqueryui.com/datepicker/#date-range

function isDateRangeValid(date1, date2) {
    var m1 = new moment(date1);
    var m2 = new moment(date2);

    if (m1.isValid() && m2.isValid()) {
        return m1 < m2;
    } else {
        return false;
    }
}

// Test the function
var testRanges = [
    ['01/10/2014','28-Dec-14'],
    ['28-Dec-2014', '27-Dec-14'],
    ['28-Dec-2014', '12/29/2014']
];

testRanges.forEach(function(entry) {
    alert('Range: ' + entry[0] + ' TO ' + entry[1] + 
      ', ISVALID: ' + 
      isDateRangeValid(entry[0],entry[1])
    );
});

      

http://jsfiddle.net/8e9j7k7v/

0


source







All Articles