Reputation: 295
I have a string '28-Dec-14' in a variable.I need to convert this string to date format. my code is
<body>
<input type="text" id="from" readonly="" />
<input type="text" id="to" readonly="" onchange="checkDate(this);"/>
</body>
here date selected by uidatepicker
my script is
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
Upvotes: 2
Views: 6300
Reputation: 447
looks like you are trying to validate a range and it'd be pretty easy, I'd just use momentjs (http://momentjs.com/). Something like this - the fiddle has more actual details. Even better if you are using jquery ui, it already has a date range that enforces to is after from 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])
);
});
Upvotes: 0
Reputation: 60
You can use javascript's Date constructor to achieve this, just pass your date string to it;
new Date(yourString);
I have modified some of your code, assuming you are using JQuery, here is a working demo:
Upvotes: 0
Reputation: 2127
No need to reinvent the wheel
var date = new Date('28-Dec-14')
Upvotes: 1
Reputation: 68440
You can do this
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var d = new Date (year,months[month],date );
Upvotes: 0