34

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?

1
  • 1
    With which code are you having trouble? Please edit your question to show what you've tried and what specifically goes wrong. Commented Feb 25, 2015 at 21:21

11 Answers 11

65

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;
Sign up to request clarification or add additional context in comments.

5 Comments

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.
@NattaWang toISOString() accepts no arguments: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
toISOString() didn't work for me but toString() did
20
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;

3 Comments

works better than the accepted answer (fixes the issue with minutes < 10)
This is the best solution on this page. Other solutions just discard the user's timezone information.
type issue galore
11

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>

4 Comments

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
@Felipe I have updated my answer with a simplest method to set inputs to locale date/ time values
4

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

1 Comment

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

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.

Comments

3

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:

  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'

Comments

1

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

Comments

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

Comments

0

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 ;

Comments

0

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;

Comments

0

its as simple as calling the function as below:

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

console.log("time", time);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.