Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getMinutes() 0-9 - How to display two digit numbers?

Tags:

javascript

var date = new Date("2012-01-18T16:03");

console.log( (date.getMinutes()<10?'0':'') + date.getMinutes() );

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"

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)


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(':');

I would like to provide a more neat solution to the problem if I may.The accepted answer is very good. But I would have done it like this.

Date.prototype.getFullMinutes = function () {
   if (this.getMinutes() < 10) {
       return '0' + this.getMinutes();
   }
   return this.getMinutes();
};

Now if you want to use this.

console.log(date.getFullMinutes());

I suggest:

var minutes = data.getMinutes();
minutes = minutes > 9 ? minutes : '0' + minutes;

it is one function call fewer. It is always good to think about performance. It is short as well;


Using ECMAScript Internationalization API, more info:

const date_string = "2012-01-18T16:03";
const date = new Date(date_string);
const twoDigitMinutes = date.toLocaleString("en-us", {year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', second: "2-digit"});

console.log(twoDigitMinutes);