Patee Gutee
Patee Gutee

Reputation: 304

How to get Formatted Date from Input Control?

I have hidden input control for date field where value comes from database:

<input data-val="true" data-val-date="The field Appointment Date must be a date." id="AppointmentDate" name="AppointmentDate" type="hidden" value="10/17/18 12:00:00 AM">

And jQuery code to get date from that control:

var appointmentdate = $('input#AppointmentDate').val();
alert(appointmentdate); // 10/17/18 12:00:00 AM

The value I get is "10/17/18 12:00:00 AM". What we need is just the date value in format MM/dd/yyyy -> "10/17/2018".

I tried searching stackoverflow but most of the situation is different where date value is actual date object which make formatting easier. In my case the date value is string? So the following jQuery code doesn't work:

var yyyy = appointmentdate.getFullYear();

Upvotes: 0

Views: 330

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

I tried searching stackoverflow but most of the situation is different where date value is actual date object which make formatting easier. In my case the date value is string?

Your research is correct in that it's much easier to format a date taken from a Date object than from a string. As such you can convert the string quite easily using the Date object constructor. From there you can pull out the required parts of the date to form the required format:

var date = new Date($('#AppointmentDate').val());
var formatted = ('00' + date.getDate()).slice(-2) + '/' + ('00' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear();

console.log(formatted);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-val="true" data-val-date="The field Appointment Date must be a date." id="AppointmentDate" name="AppointmentDate" type="hidden" value="10/17/18 12:00:00 AM">

Note that you have to add 1 to getMonth() as it returns months numbers as a zero-based set.

Upvotes: 2

Sooriya Dasanayake
Sooriya Dasanayake

Reputation: 1156

This is right way... other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31

var date = new Date($('#AppointmentDate').val());
var formatDate =getFormattedDate(date);
console.log(formatDate);

function getFormattedDate(date) {
  var year = date.getFullYear();

  var month = (1 + date.getMonth()).toString();
  month = month.length > 1 ? month : '0' + month;

  var day = date.getDate().toString();
  day = day.length > 1 ? day : '0' + day;
  
  return month + '/' + day + '/' + year;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-val="true" data-val-date="The field Appointment Date must be a date." id="AppointmentDate" name="AppointmentDate" type="hidden" value="10/17/18 12:00:00 AM">

Upvotes: 1

Related Questions