Last active
May 31, 2017 16:32
-
-
Save ryanburnette/8803238 to your computer and use it in GitHub Desktop.
A jQuery method that sets datetime fields to the current UTC time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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; | |
} |
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'));
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
correction:
month = (now.getMonth() + 1).toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;