0

sorry for another question here,

I'm trying to get values from html input type date and time, but I seem to run into some issues and need some guidance from any of you.

What I'm trying to do here is, when any user selects the date, it will populate the value with the format "MM-DD".

For example,

<input type="date" name="departure_1" id="depature_1" />
<input type="date" name="arrival_2" id="arrival_2" />

The output should look something like:

Departure Date: 10-24 Arrival Date: 11-24

What I have figured out so far is, I can do something similar to below to change the date format, but I can't seem to think a way to implement this in a function and get what I'm looking for

var result = enteredDate.getMonth() + "" + enteredDate.getDate()

Any help would be greatly appreciated.

3 Answers3

0

So make it a function, remembering that month number in JS begin at 0 and that you need to pad with a leading zero.

var result = getMMDD(document.getElementById("dateinput").valueAsDate);

function getMMDD(date) {
   return ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2)
}
Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • As with Taiti's answer, this will show the day before for users west of Greenwich for the same reason. – RobG Dec 12 '16 at 23:47
0

Not all browsers support input type date, but I'll let you deal with that. For those that do support it, the value is formatted per ISO 8601, i.e. yyyy-mm-dd. If you pass that to the Date constructor, it will be treated as UTC so for users west of Greenwich, the date will appear to be the day before, e.g. 2016-12-12 for a user on the east coast of the USA will be 2016-12-11 at 19:00.

But if you just want to show the date as mmdd, you don't need a Date object at all, just reformat the string:

function showMMDD(d) {
  var b = d.split('-')
  var el = document.getElementById('formatedDate');
  if (el) {
    el.textContent = b[1] + '-' + b[2];
  }
}
<input type="date" value="2016-12-15" onblur="showMMDD(this.value)">
<p>Date as mm-dd: <span id="formatedDate"></span></p>
RobG
  • 142,382
  • 31
  • 172
  • 209
-1

You have to do this

var result = new Date(enteredDate).getMonth()+1+""+ new Date(enteredDate).getDate()
Taiti
  • 375
  • 2
  • 6
  • No, don't do that. The value of a date input is ISO 8601, i.e. yyyy-mm-dd. When parsed by the Date constructor (or Date.parse) it's treated as UTC so for users west of Greenwich, the date will appear to be the day before the date chosen. – RobG Dec 12 '16 at 23:44