What is the correct way to set and get HTMLInputElement.valueAsDate using local Dates?

Viewed 6887

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?

1 Answers

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());

Related