JavaScript Add Leading Zeroes to Date

Javascript add leading zeroes to date

Try this: http://jsfiddle.net/xA5B7/

var MyDate = new Date();
var MyDateString;

MyDate.setDate(MyDate.getDate() + 20);

MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
+ ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
+ MyDate.getFullYear();

EDIT:

To explain, .slice(-2) gives us the last two characters of the string.

So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.

So if the MyDate.getMonth() returns 9, it will be:

("0" + "9") // Giving us "09"

so adding .slice(-2) on that gives us the last two characters which is:

("0" + "9").slice(-2)
"09"

But if MyDate.getMonth() returns 10, it will be:

("0" + "10") // Giving us "010"

so adding .slice(-2) gives us the last two characters, or:

("0" + "10").slice(-2)
"10"

How to add leading zeros to the result of a date difference calculation, using moment.js?

Simple if statement to prepend a 0 will work -- typeof diff() value returns number and you need to convert to a string to manipulate.

Date.getFormattedDateDiff = function(date1, date2) {
var b = moment(date1),
a = moment(date2),
intervals = ['years','months','weeks','days','hours','minutes','seconds'],
out = [];

for(var i=0; i<intervals.length; i++){
var diff = a.diff(b, intervals[i]);
b.add(diff, intervals[i]);
if (diff.toString().length == 1) {
diff = "0" + diff.toString();
}
out.push('<div>' + diff + ' ' + intervals[i] + '</div><br/>');
}
return out.join(' ');
};

window.onload = function calculateInterval() {
var start = moment("2013-09-04"),
end = moment();

document.getElementById('output').innerHTML
= 'Time elapsed between "' + start.toISOString().split('T')[0]
+ '" and "' + end.toISOString().split('T')[0] + '":<br/><br/>'
+ Date.getFormattedDateDiff(start, end);
}

You can also refer to this thread for some fantastic leading 0 methods.

Javascript Slicing date/time with leading zero

You can check for the variable length of characters, if is less than two, then add a 0.

Something like this:

var d = new Date();

var day = d.getDate();

var month = d.getMonth() + 1;

var year = d.getFullYear();

var hour = d.getHours();

var minute = d.getMinutes();

var second = d.getSeconds();

if (month.toString().length < 2) month = '0' + month;

if (hour.toString().length < 2) hour = '0' + hour;

if (minute.toString().length < 2) minute = '0' + minute;

if (second.toString().length < 2) second = '0' + second;

console.log(year + '-' + month + '-' + day + " " + hour + ":" + minute + ":" + second)

Digits with leading zero in date and time

You can use the following:

var x1 =   ('0' + x.getDate()).slice(-2)      + '/'
+ ('0' + (x.getMonth()+1)).slice(-2) + '/'
+ x.getFullYear() + '-'
+ ('0' + x.getHours()).slice(-2) + ':'
+ ('0' + x.getMinutes()).slice(-2) + ':'
+ ('0' + x.getSeconds()).slice(-2);

Add leading zeroes to a moment.js time

You can use moment-duration format plug-in:

Use the trim option to show units that have no value. As the docs says:

Leading tokens are automatically trimmed when they have no value. To stop that behavior, set { trim: false }.

Here a working example:

var d1 = moment.duration({

seconds: 23,

minutes: 12,

hours: 1,

days: 9

});

var d2 = moment.duration({

minutes: 1

});

console.log(d1.format('DD:HH:mm:ss'));

console.log(d2.format('DD:HH:mm:ss', { trim: false }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

JS Date() - Leading zero on days

According to ECMA-262 (5.1):

The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

The date/time string format as described in 15.9.1.15 is YYYY-MM-DDTHH:mm:ss.sssZ. It can also be a shorter representation of this format, like YYYY-MM-DD.

2015-11-1 is not a valid date/time string for Javascript (note it's YYYY-MM-D and not YYYY-MM-DD). Thus, the implementation (browser) is able to do whatever it wants with that string. It can attempt to parse the string in a different format, or it can simply say that the string is an invalid date. Chrome chooses the former (see DateParser::Parse) and attempts to parse it as a "legacy" date. Firefox seems to choose the latter, and refuses to parse it.

Now, your claim that new Date('2015-11-01') doesn't work in Chrome is incorrect. As the string conforms to the date/time string format, Chrome must parse it to be specification compliant. In fact, I just tried it myself -- it works in Chrome.

So, what are your options here?

  1. Use the correct date/time format (i.e. YYYY-MM-DD or some extension of it).

  2. Use the new Date (year, month, date) constructor, i.e. new Date(2015, 10, 1) (months go from 0-11) in this case.

Whichever option is up to you, but there is a date/time string format that all specification compliant browsers should agree on.

Adding leading zero with javascript?

Try the following code:

var currentDate = new Date();

//currentDate.setMonth(currentDate.getMonth() + 7);

var day = currentDate.getDate()

if(day <= 9)

day = '0'+day;

var month = currentDate.getMonth() + 1

if(month <= 9)

month = '0'+month;

var year = currentDate.getFullYear()

document.getElementById("element_183").value =("" + month + "/" + day + "/" + year + "")

function DateFromString(str){

str = str.split(/\D+/);

str = new Date(str[2],str[0]-1,(parseInt(str[1])+90));



return str;

}

function MMDDYYYY(str) {

var ndateArr = str.toString().split(' ');

var Months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec';

var str = new Date(str);



var day = str.getDate();

if(day <= 9)

day = '0'+day;

var month = str.getMonth() + 1

if(month <= 9)

month = '0'+month;

var year = str.getFullYear()

return ("" + month + "/" + day + "/" + year + "");

}

function Add90Days() {

var date = $('#element_183').val();

var ndate = MMDDYYYY(DateFromString(date));

return ndate;

}

$('#element_183').ready(function(){

$('#element_184').val(Add90Days());

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Enter date:<input type="text" id="element_183" readonly>

Next date:<input type="text" id="element_184" readonly>


Related Topics



Leave a reply



Submit