Sameera Silva
Sameera Silva

Reputation: 453

Moment.js "Invalid date"

I just tried to make a text input with formatted date. It is working fine on Google Chrome, but when I run it on Mozilla Firefox (26.0) it says: Invalid date.

You can see and run my example in both browsers and hopefully understand the problem.

JS Code:

$( "#h_reg_date" ).datepicker();
$("#h_reg_date").datepicker("option", "dateFormat", "yy-M-dd");

$("#save_data").on("click", function(){
 var reg_date = $("#h_reg_date").val();
  console.log(reg_date);
  reg_date =  moment(reg_date).format("YYYY/MM/DD");
  console.log(reg_date);
  return;
});

HTML:

<input type="text" id="h_reg_date"class="abs" style="top:135px; left:150px;" size="10" readonly >
<input type="button" id="save_data" class="abs" style="top:370px; left:-200px;" value="Add Data">

Is there any solution to this problem?

Upvotes: 34

Views: 112243

Answers (3)

Sachin T Sawant
Sachin T Sawant

Reputation: 759

Suppose your date is in format 'DD-MM-YYYY' & you want to display it in DD-MMM format then you can do this by first telling moment function which format your date currently is & then asking it to convert it to required format. Below is the example:

var taskDueDate = moment(dueDate, 'DD-MM-YYYY').format('DD-MMM');

This way you can convert your date in any format.

Upvotes: 52

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

Change the format of the datepicker to:

$("#h_reg_date").datepicker("option", "dateFormat", "yy/mm/dd");

JS Fiddle: http://jsfiddle.net/MMm86/1/

To put the date in your requested format use:

$( "#h_reg_date" ).datepicker();
$("#h_reg_date").datepicker("option", "dateFormat", "yy/M/dd");

$("#save_data").on("click", function(){
 var reg_date = $("#h_reg_date").val();
  console.log(reg_date);
  reg_date =  moment(reg_date).format("YYYY/MMM/DD");
  console.log(reg_date);
  return;
});

JS Fiddle: http://jsfiddle.net/MMm86/2/

Upvotes: 10

thescientist
thescientist

Reputation: 2948

It seems to be a known issue, per their docs. http://momentjs.com/docs/#/parsing/string/

Looks like they suggest passing in the time string and the format.

Upvotes: 5

Related Questions