Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 910
HelloWorld Avatar asked Oct 28 '18 15:10

HelloWorld


People also ask

How can set input type date in mm/dd/yyyy format using HTML?

To set and get the input type date in dd-mm-yyyy format we will use <input> type attribute. The <input> type attribute is used to define a date picker or control field. In this attribute, you can set the range from which day-month-year to which day-month-year date can be selected from.

How can get current date in textbox in HTML?

<input type="text" name="frmDateReg" required id="frmDate" value=""> function getDate(){ var todaydate = new Date(); var day = todaydate. getDate(); var month = todaydate. getMonth() + 1; var year = todaydate.


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());
like image 148
Bergi Avatar answered Sep 19 '22 03:09

Bergi