Set values in input type date and time in javascript
With which code are you having trouble? Please edit your question to show what you’ve tried and what specifically goes wrong.
11 Answers 11
You can just set the value of the input field with the respective formats:
Using your example, you can do something simple like:
var date = new Date(); var currentDate = date.toISOString().substring(0,10); var currentTime = date.toISOString().substring(11,16); document.getElementById('currentDate').value = currentDate; document.getElementById('currentTime').value = currentTime;
Your code doesn’t work if getHours() or getMinutes() returns values under 10 . The time input will reject strings like «4:8» . You need to ensure that each component (hours and minutes) has a leading zero, e.g. «04:08»
What does » .slice(0,10) » does? Does it take the first 10 digits and set them for the appropriate date format ? Do you have any helpful links ?
.toISOString() only might cause a bug issue, because default it will calculate UTC conversion, to prevent it automate calculate, you should call with toISOString(true) to achieve it.
var date = new Date(); var day = date.getDate(), month = date.getMonth() + 1, year = date.getFullYear(), hour = date.getHours(), min = date.getMinutes(); month = (month < 10 ? "0" : "") + month; day = (day < 10 ? "0" : "") + day; hour = (hour < 10 ? "0" : "") + hour; min = (min < 10 ? "0" : "") + min; var today = year + "-" + month + "-" + day, displayTime = hour + ":" + min; document.getElementById('formdate').value = today; document.getElementById("formtime").value = displayTime;
This is the best solution on this page. Other solutions just discard the user's timezone information.
On modern browsers, this is very simple:
just use HTML_element .valueAsDate instead of HTML_element .value
const myForm = document.querySelector('#my-form') , dtStr = document.querySelector('#date-time-Str') , localDt_now =_=> < let now = new Date() now.setMinutes(now.getMinutes() - now.getTimezoneOffset()) now.setSeconds(0) // remove seconds now.setMilliseconds(0) // remove milliseconds return now >/* ------------------------------------------- *\ * set date & time ! * \* ------------------------------------------- */ myForm.inDate.valueAsDate = localDt_now() // current date myForm.inTime.valueAsDate = localDt_now() // current time /*----------------------------------- Bonus -*\ * some Intl methods to use. * \*-------------------------------------------*/ const fxD = // dates Formats < ymd : Intl.DateTimeFormat( 0, < year: 'numeric', month: '2-digit', day: '2-digit' >) , hm : Intl.DateTimeFormat( 0, < hour12: false, hour: '2-digit', minute: '2-digit' >) > , fxD_parts = (d,fx) => fx.formatToParts(d).reduce((o,)=>(o[type]=value,o),<>) ; /*------------------------------------ Bonus -*\ * reverse action = get date & time values ! * \*--------------------------------------------*/ // add TZ offset to get locale values const getLocalDt = dt => dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset()) /*----------------------------------- Bonus -*\ * demo. * \*-------------------------------------------*/ myForm.onsubmit = e => < e.preventDefault() let dt_D = fxD_parts( getLocalDt( myForm.inDate.valueAsDate), fxD.ymd ) , dt_T = fxD_parts( getLocalDt( myForm.inTime.valueAsDate), fxD.hm ) ; dtStr.innerHTML = ` date = $- $ - $
` + ` time = $ : $` >
d=. t=.
// just my preference to access form elements by names const myForm = document.querySelector('#my-Form') // 1: get local date and time values let sysDate = new Date() , userDate = new Date(Date.UTC(sysDate.getFullYear(), sysDate.getMonth(), sysDate.getDate(), sysDate.getHours(), sysDate.getMinutes(), 0)); // 2: set interface values ! myForm.currentDate.valueAsDate = userDate myForm.currentTime.valueAsDate = userDate
great answer, although I have found that valueAsDate will use the UTC time of the date. I haven't found a clean solution yet
yes, internally. But when it comes to displaying the time, it is most often the case that you want to show it in the client zone. See this quick example: jsfiddle.net/jtmLv0dc
I can no longer edit my comment, but what it was intended to say is valueAsDate will display the UTC time of the date
I find that using ISOString, the format is, of course, standardised. You can simply split the string at 'T' for an array of date and time (Zulu included, you may wish to splice out the last char, 'Z').
Thus, the simplest solution I found was merely to:
let tmp = new Date(Date.now()); // tmp now like: "2018-08-21T11:54:50.580Z" let dateInputFormatted = tmp.toISOString().split('T')[0]; // 0, as split produces: ["2018-08-21", "11:54:50.580Z"] console.log(dateInputFormatted);
This is not an ideal solution as it disregards the timezone information. For example: new Date('2019-08-17T01:42:30.809680+05:30') is in user's local timezone. If you use .getDate() , you'll get user's local date -- 17 . But on doing .toISOString().split('T') , you get the UTC date -- 16 , which is one day behind.
You can make two prototypes in order to reuse them:
Date.prototype.dateToInput = function() < return this.getFullYear() + '-' + ('0' + (this.getMonth() + 1)).substr(-2,2) + '-' + ('0' + this.getDate()).substr(-2,2); >Date.prototype.timeToInput = function()
var date = new Date(); document.getElementById('currentDate').value = date.dateToInput(); document.getElementById('currentTime').value = date.timeToInput();
var date = new Date(); var dateOptions = < day: '2-digit', month: '2-digit', year: 'numeric' >; var currentDate = date.toLocaleDateString('ja-JP', dateOptions).replace(/\//gi, '-'); var timeOptions = < hour: '2-digit', minute: '2-digit' >; var currentTime = date.toLocaleTimeString('it-IT', timeOptions); document.getElementById('currentDate').value = currentDate; document.getElementById('currentTime').value = currentTime;
In order to convert a date to an ISO date without the time, you need to use the getDate , getMonth , etc. methods instead of getting the ISOString directly and manipulating the string. The latter will not take the timezone into consideration which will lead to unexpected results.
Here is a solution for the same using ES6.
// Function which returns a minimum of two digits in case the value is less than 10 const getTwoDigits = (value) => value < 10 ? `0$` : value; const formatDate = (date) => < const day = getTwoDigits(date.getDate()); const month = getTwoDigits(date.getMonth() + 1); // add 1 since getMonth returns 0-11 for the months const year = date.getFullYear(); return `$-$-$`; > const formatTime = (date) => < const hours = getTwoDigits(date.getHours()); const mins = getTwoDigits(date.getMinutes()); return `$:$`; > const date = new Date(); document.getElementById('currentDate').value = formatDate(date); document.getElementById('currentTime').value = formatTime(date);
This will now return the current date and time as per the current timezone.
How can I set these fields to the current date/time?
If you want the date/time of the browser/client in local time (not in UTC/GMT!) then use
var date = new Date(); document.getElementById('currentDate').valueAsDate = date; document.getElementById('currentTime').value = date.toTimeString().substring(0,5);
If you want more time granularity (e.g. also seconds) then enhance the "5" in the substring (e.g. to "8"). Modern browsers provide date/time pickers, enlarge the time entry field from the value provided and also respect the browsers "language/date-time format" preferences. Above solution sets date and time (hours and minutes) correctly for any browsers "language/date-time format" preferences.
Problems with other solutions are:
- Date.toISOString() provides UTC/Zulu time
- toLocaleTimeString might provide "9:12" instead of the required "09:12":
- date.toLocaleTimeString('it-IT', < hour: '2-digit', minute: '2-digit' >) works but date.toTimeString().substring(0,5) is shorter and without the need to pick any Locale such as 'it-IT'
Date.prototype.setDate()
The setDate() method of Date instances changes the day of the month for this date according to local time.
Try it
Syntax
Parameters
An integer representing the day of the month.
Return value
Changes the Date object in place, and returns its new timestamp. If dateValue is NaN (or other values that get coerced to NaN , such as undefined ), the date is set to Invalid Date and NaN is returned.
Description
If you specify a number outside the expected range, the date information in the Date object is updated accordingly. For example, if the Date object holds June 1st, a dateValue of 40 changes the date to July 10th, while a dateValue of 0 changes the date to the last day of the previous month, May 31st.
Examples
Using setDate()
const theBigDay = new Date(1962, 6, 7, 12); // noon of 1962-07-07 (7th of July 1962, month is 0-indexed) const theBigDay2 = new Date(theBigDay).setDate(24); // 1962-07-24 (24th of July 1962) const theBigDay3 = new Date(theBigDay).setDate(32); // 1962-08-01 (1st of August 1962) const theBigDay4 = new Date(theBigDay).setDate(22); // 1962-07-22 (22nd of July 1962) const theBigDay5 = new Date(theBigDay).setDate(0); // 1962-06-30 (30th of June 1962) const theBigDay6 = new Date(theBigDay).setDate(98); // 1962-10-06 (6th of October 1962) const theBigDay7 = new Date(theBigDay).setDate(-50); // 1962-05-11 (11th of May 1962)
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 28, 2023 by MDN contributors.
Your blueprint for a better internet.