Reading the date from textbox as a string and converting it into as Date

3.9k views Asked by At

I am reading the date from textbox by using javascript and trying to convert it as Date object.But my problem is date is converting as month and month is converting as date when converting the string to date.

Example: 03/12/2014 the value in the textbox

Actual Output: 03 as March, 12 as date (Its wrong)

Expected Output: 03 as date 12 as December (I am expecting)

While converting this string to date by using following snippet

var startTime = document.getElementById("meeting:startTime");
date.js
var stringToDate_startTime=new Date(Date.parse(startTime.value,"dd/mm/yy"));
moment.js
var date1=moment(startTime.value).format('DD-MM-YYYY');

In the above even i have used date.js and moment.js files also.But those also did not solve my problem.Please can anyone help me out to get rid out of this.

2

There are 2 answers

2
rfornal On

Try ...

var from = startTime.value.split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);

... assuming time included ...

var date_only = startTime.value.split("");
var from = date_only[0].split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
4
Albert Pucciani On

I am not aware of an implementation of the Date.parse() method that accepts two arguments. You can view the Mozilla Date.parse() method description here Date.parse() - JavaScript | MDN.

It might be worth looking at the question/answer of this question for some more information: Why does Date.parse give incorrect results?

The next best option would be to split the date using String.split() and to rearrange the date parts

var dateStr = '03/12/2014 23:05';
var newDateStr = null;
var dateParts = dateStr.split('/');
if (dateParts.length == 3) {
   var day = dateParts[0];
   var month = dateParts[1];
   var yearAndTime = dateParts[2];

   // Rearrange the month and day and rejoin the date "12/03/2014 23:05"
   newDateStr = [ month, day, yearAndTime].join('/');
} else {
   throw new Error('Date not in the expected format.');
}

var date = new Date(newDateStr);   // JS Engine will parse the string automagically

alert(date);

This isn't the most elegant solution, but hopefully that helps.