Reputation: 719
I've an input that is filled by jQuery/JS. Currently it fills the input with a date value like this 2017-3-7
but I want it to be 2017-03-07
.
I've a jsfiddle here: https://jsfiddle.net/ua8rngzw/
And the code is as follows:
(function ($) {
$(document).ready(function() {
var now = new Date();
var created = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
$('#created').val(created);
});
})(jQuery);
What is the easiest and quickest way to do such a thing?
Upvotes: 3
Views: 9786
Reputation: 65853
We can create a simple function that takes in a value and based on its length, pre-pends a zero to it. Then, take your date portions and run them through the function:
(function ($) {
$(document).ready(function() {
var now = new Date();
var created = now.getFullYear() + '-' +
fixDigit(now.getMonth() + 1) +
'-' + fixDigit(now.getDate());
$('#created').val(created);
});
// Utility function to prepend zeros to single digits:
function fixDigit(val){
return val.toString().length === 1 ? "0" + val : val;
}
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="created">
Upvotes: 9
Reputation: 175
The possible solution is:
(function ($) {
$(document).ready(function() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
var created = yyyy+'-'+mm+'-'+gg;
document.write(created);
})(jQuery);
Upvotes: 0
Reputation: 14321
(function ($) {
$(document).ready(function() {
var now = new Date();
mo = now.getMonth() + 1;
if (mo < 10) {
mo = "0" + mo;
}
date = now.getDate();
if (date < 10) {
date = "0" + date;
}
var created = now.getFullYear() + '-' + mo + '-' + date;
$('#created').val(created);
});
})(jQuery);
Upvotes: 1