getMinutes() 0-9 - How to display two digit numbers?
Another short way is to fill the minutes with a leading zero using:
String(date.getMinutes()).padStart(2, "0");
Meaning: Make the string two chars long, if a char is missing then set 0
at this position.
See docs at str.padStart(targetLength, padString)
Yikes these answers aren't great, even the top post upticked. Here y'go, cross-browser and cleaner int/string conversion. Plus my advice is don't use a variable name 'date' with code like date = Date(...)
where you're relying heavily on language case sensitivity (it works, but risky when you're working with server/browser code in different languages with different rules). So assuming the javascript Date in a var current_date
:
mins = ('0'+current_date.getMinutes()).slice(-2);
The technique is take the rightmost 2 characters (slice(-2))
of "0" prepended onto the string value of getMinutes()
. So:
"0"+"12" -> "012".slice(-2) -> "12"
and
"0"+"1" -> "01".slice(-2) -> "01"
Elegant ES6 function to format a date into hh:mm:ss
:
const leadingZero = (num) => `0${num}`.slice(-2);
const formatTime = (date) =>
[date.getHours(), date.getMinutes(), date.getSeconds()]
.map(leadingZero)
.join(':');
var date = new Date("2012-01-18T16:03");
console.log( (date.getMinutes()<10?'0':'') + date.getMinutes() );