11

The functionality of valueAsDate seems fundamentally flawed:

var date1 = new Date();
date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate()); // input expects requires year, month, day

var input = document.createElement("input"); input.type = "date";

input.valueAsDate = date1;

var date2 = input.valueAsDate;

console.log(date1);
console.log(date2);

console.log(date1.getTime(), date2.getTime()); // EVEN THE UTC TIMESTAMP IS NOT EQUAL!!

I want to set a local Date, and I want to get a local Date. How can this be achieved all the while maintaining the correct Date kind (UTC or local) back and forth?

HelloWorld
  • 3,381
  • 5
  • 32
  • 58
  • I don't see anything unexpected. The input strips off the time part and preserves only the date portion. – Bergi Oct 28 '18 at 15:15
  • @Bergi valueAsDate seems to expect UTC, and as such, if I'm living at GMT +1, then at one hour of the day, the date part will become different – HelloWorld Oct 28 '18 at 15:37
  • That seems reasonable. In that case, use the `UTC` getter methods to access the date. If you are showing local times elsewhere, you will need to "convert" unfortunately. – Bergi Oct 28 '18 at 15:41
  • @Bergi Yes, I'm currently unsure how to do this correctly :) – HelloWorld Oct 28 '18 at 15:53
  • related: [How do you parse a date from an HTML5 date input?](https://stackoverflow.com/q/16825363/1048572) and [HTML input type date and time without timezone offset](https://stackoverflow.com/q/36486117/1048572) – Bergi Oct 28 '18 at 15:55

1 Answers1

9

The days shown on the <input type="date"> are UTC days. If you want to treat them as local days, you will need to adjust the Date objects:

var date1 = new Date(); // now
var input = document.createElement("input"); input.type = "date";

input.valueAsDate = new Date(Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate()));

var midnightUtcDate = input.valueAsDate;
var date2 = new Date(midnightUtcDate.getUTCFullYear(), midnightUtcDate.getUTCMonth(), midnightUtcDate.getUTCDate());

console.log(date1, date1.toLocaleDateString());
console.log(date2, date2.toLocaleDateString());
Bergi
  • 630,263
  • 148
  • 957
  • 1,375