Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

eayavuz commented Oct 30, 2015

correction:

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

@joeyhub

This comment has been minimized.

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

This comment has been minimized.

Copy link
Owner Author

ryanburnette commented May 31, 2017

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
You can’t perform that action at this time.