Skip to content

Instantly share code, notes, and snippets.

@mattbell87
Created July 15, 2016 01:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattbell87/72b19104f2aa4fa54e11956158b01863 to your computer and use it in GitHub Desktop.
Save mattbell87/72b19104f2aa4fa54e11956158b01863 to your computer and use it in GitHub Desktop.
Setting the current date and time on a HTML5 date or datetime field with Javascript

Setting the current date and time on a HTML5 date or datetime field with Javascript

By default date.toISOString returns UTC time instead of local time. So you'll need to calculate the timezone offset first.

//Get the local date in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 10);

//Set the field value
var field = document.querySelector('#date');
field.value = datestr;

If it's a datetime field you're modifying (as opposed to just the date) don't forget to add the time T00:00, or change the substring to 16 characters for example:

//Get the local date and time in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 16);

//Set the field value
var field = document.querySelector('#datetime');
field.value = datestr;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment