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

Javascript

Javascript Problem Overview


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

console.log(date.getMinutes());
console.log(date.getMinutes().length)

This returns 3.

  1. How do I make it return '03'?
  2. Why does .length return undefinded?

I tried this, but it did not work:

If strlen == 1 then num = ('0' + num);

Javascript Solutions


Solution 1 - Javascript

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

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

Solution 2 - Javascript

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"

Solution 3 - Javascript

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)

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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);

Solution 7 - Javascript

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;

Solution 8 - Javascript

Another option:

var dateTime = new Date();
var minutesTwoDigitsWithLeadingZero = ("0" + dateTime.getMinutes()).substr(-2);

Solution 9 - Javascript

you should check if it is less than 10... not looking for the length of it , because this is a number and not a string

Solution 10 - Javascript

I assume you would need the value as string. You could use the code below. It will always return give you the two digit minutes as string.

const date_string = "2012-01-18T16:03"; const date = new Date(date_string); let min = date.getMinutes();

if (min < 10) { // or min = min < 10 ? '0' + min : min; min = '0' + min; } else { min = min + ''; }

console.log(min);

Hope this helps.

Solution 11 - Javascript

how about this? it works for me! :)

var d = new Date();
var minutes = d.getMinutes().toString().replace(/^(\d)$/, '0$1');

Solution 12 - Javascript

.length is undefined because getMinutes is returning a number, not a string. numbers don't have a length property. You could do

var m = "" + date.getMinutes();

to make it a string, then check the length (you would want to check for length === 1, not 0).

Solution 13 - Javascript

Numbers don't have a length, but you can easily convert the number to a string, check the length and then prepend the 0 if it's necessary:

var strMonth = '' + date.getMinutes();
if (strMonth.length == 1) {
strMonth = '0' + strMonth;
}

Solution 14 - Javascript

I dont see any ES6 answers on here so I will add one using StandardJS formatting

// ES6 String formatting example
const time = new Date()
const tempMinutes = new Date.getMinutes()
const minutes = (tempMinutes < 10) ? `0${tempMinutes}` : tempMinutes

Solution 15 - Javascript

const date_string = "2012-01-18T16:03"; const date = new Date(date_string); const dd = date.getDate(); const MM = date.getMonth(); const mm = date.getMinutes(); const HH = date.getHours();

// Year
const year = date.getFullYear();

// Month
const month = ("0" + (MM + 1)).slice(-2); // first month start from 0, so add +1

// Day
const day = ("0" + dd).slice(-2);

// Hour
const hour = ("0" + HH).slice(-2);

// Minutes
const minutes = ("0" + mm).slice(-2);

// Seconds
const seconds = ("0" + mm).slice(-2);

console.log(year, month, day, hour, minutes, seconds);

Solution 16 - Javascript

I usually use this piece of code :

var start = new Date(timestamp),
    startMinutes = start.getMinutes() < 10 ? '0' + start.getMinutes() : start.getMinutes();

It is quite similar to the @ogur accepted answer but does not concatenate an empty string in the case that 0 is not needed. Not sure it is better. Just an other way to do it !

Solution 17 - Javascript

$(".min").append( (date.getMinutes()<10?'0':'') + date.getMinutes() );

new to JS so this was very helpful the most ppl looking at this prob new too so this is how i got it to show in the div called "class="min"

hope it helps someone

Solution 18 - Javascript

Another option to get two digit minutes or hours.

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

var minutes = date.toTimeString().slice(3, 5); 
var hours   = date.toTimeString().slice(0, 2); 

Solution 19 - Javascript

You can use moment.js :

> moment(date).format('mm')

example : moment('2019-10-29T21:08').format('mm') ==> 08

hope it helps someone

Link github:
https://github.com/moment/moment/

Solution 20 - Javascript

For two digit minutes use: new Date().toLocaleFormat("%M")

Solution 21 - Javascript

If you're using AngularJS in your project, just inject $filter and use it like here:

$filter('date')(value, 'HH:mm')

You can also format the output in the template, more on filters here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark FondyView Question on Stackoverflow
Solution 1 - JavascriptogurView Answer on Stackoverflow
Solution 2 - JavascriptBambamView Answer on Stackoverflow
Solution 3 - JavascriptAvatarView Answer on Stackoverflow
Solution 4 - Javascriptsf77View Answer on Stackoverflow
Solution 5 - JavascriptKapteinMarshallView Answer on Stackoverflow
Solution 6 - JavascriptHamid MosallaView Answer on Stackoverflow
Solution 7 - Javascriptuser2846569View Answer on Stackoverflow
Solution 8 - JavascriptIanGSYView Answer on Stackoverflow
Solution 9 - JavascriptYaron U.View Answer on Stackoverflow
Solution 10 - JavascriptAndrew L.View Answer on Stackoverflow
Solution 11 - JavascriptYuri MView Answer on Stackoverflow
Solution 12 - JavascripthvgotcodesView Answer on Stackoverflow
Solution 13 - JavascriptGlennView Answer on Stackoverflow
Solution 14 - JavascriptJordan PapaleoView Answer on Stackoverflow
Solution 15 - JavascriptIsrael Nunes orienteView Answer on Stackoverflow
Solution 16 - JavascriptJRMLSTFView Answer on Stackoverflow
Solution 17 - JavascriptJason TeunissenView Answer on Stackoverflow
Solution 18 - JavascriptKasper KampermanView Answer on Stackoverflow
Solution 19 - JavascriptYounes OuchalaView Answer on Stackoverflow
Solution 20 - Javascriptz3roneView Answer on Stackoverflow
Solution 21 - Javascripteso32View Answer on Stackoverflow