Skip to content

Instantly share code, notes, and snippets.

@ryanburnette
Last active May 31, 2017 16:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanburnette/8803238 to your computer and use it in GitHub Desktop.
Save ryanburnette/8803238 to your computer and use it in GitHub Desktop.
A jQuery method that sets datetime fields to the current UTC time.
$.fn.setNow = function (onlyBlank) {
var now = new Date($.now());
var year = now.getFullYear();
var month = (now.getMonth() + 1).toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
var date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
var hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours();
var minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes();
var seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();
var formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds;
if ( onlyBlank === true && $(this).val() ) {
return this;
}
$(this).val(formattedDateTime);
return this;
}
@eayavuz
Copy link

eayavuz commented Oct 30, 2015

correction:

month = (now.getMonth() + 1).toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;

@joeyhub
Copy link

joeyhub commented Oct 31, 2016

This is probably a better way to do it:

$('input[type=datetime-local]').prop('valueAsNumber', Math.floor(new Date() / 60000) * 60000); // 60seconds * 1000milliseconds

It might not work for all browsers. You could feature detect.

If you do:

var x = $('input[type=datetime-local]')[0];

Into your console for each browser you can auto-complete to see what they have.

I've discovered with this there's some support for milliseconds as well which is not included here.

Also you should just make it take a parameter. All now is is new Date(). It makes more sense to have that as a parameter so it's more flexible. You can call it setDate instead or something.

Date type coerces to a long of milliseconds unixtime (always UTC I believe) or something similar with numeric operations.

You can also do a getter with:

new Date($(this).prop('valueAsNumber'));

@ryanburnette
Copy link
Author

I made the change to month suggested by @eayavuz.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment