Set values in input type date and time in javascript

I have two input fields:

<input type="date" id="currentDate">
<input type="time" id="currentTime">

How can I set these fields to the current date/time?

You can just set the value of the input field with the respective formats:

  • date is yyyy-MM-dd
  • time is HH:mm

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;

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;

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,{type,value})=>(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 = ${dt_D.year} - ${dt_D.month} - ${dt_D.day} <br>`
                  + ` time = ${dt_T.hour} : ${dt_T.minute}` 
  }
form {
  padding       : 1em 2em;
  }
label {
  display       : inline-block;
  line-height   : 1.3em;
  margin        : 1em .6em;
  font-size     : .8em;
  }
input {
  display       : block;
  margin-bottom : .6em;
  }
<form id="my-form" method="post" action="#">
  <label>
    Date:
    <input name="inDate" type="date">
  </label>
  <label>
    Time: 
    <input name="inTime" type="time">
  </label>
  <br><br>
  <button type="submit">get Date & time (Bonus)</button>
</form>

<p id="date-time-Str">d=??? t=???</p>

(previous version)

// 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
<form action="xxx" id="my-Form">

  <input type="date" name="currentDate">
  <br><br>
  <input type="time" name="currentTime">

</form>

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’).

Read More:   How to call a function before leaving page with Javascript

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

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(){
        return  ('0' + (this.getHours())).substr(-2,2) + ':' + ('0' + this.getMinutes()).substr(-2,2);
    }

Then use them like this:

    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}` : 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 `${year}-${month}-${day}`;
}

const formatTime = (date) => {
  const hours = getTwoDigits(date.getHours());
  const mins = getTwoDigits(date.getMinutes());

  return `${hours}:${mins}`;
}

const date = new Date();
document.getElementById('currentDate').value = formatDate(date);
document.getElementById('currentTime').value = formatTime(date);
<input type="date" id="currentDate">
<input type="time" id="currentTime">

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.

Read More:   How to inherit static methods from base class in JavaScript?

Problems with other solutions are:

  1. Date.toISOString() provides UTC/Zulu time

  2. toLocaleTimeString might provide “9:12” instead of the required “09:12”:

  3. 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’

Suppose, you have a date (text) value in any text format.

Eg. myDate = 28-08-2020;

Now, to set it on <input type="date"/> you need to bring the date in “YYYY-MM-DD” format.

So,

var tempD = date.split("-");
myDate = tempD[2] + "-" + tempD[1] + "-" + tempD[0]; //myDate will be = 2020-08-28
document.getElementById("myDate").value = myDate ;

you can use this code

<input type="date" id="currentDate">

and in your script , write this code

var date = new Date();

var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day +"T00:00";       
document.getElementById("currentDate").value = today;

its as simple as calling the function as below:

var time = new Date()
  .toLocaleTimeString("en-US", {
      hour12: false
  });

console.log("time", time);


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts