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

Jerry Chong
  • 7,954
  • 4
  • 45
  • 40
Mark Fondy
  • 3,773
  • 8
  • 24
  • 25
  • Just to add up, the return of `.getMinutes()` is an integer, you can't access `.length` from an integer. To accomplish that (not recommended when dealing with dates) is parsing the number to a string and then checking the length. E.g.: `date.getMinutes().toString().length` – ViniciusPires Jul 26 '13 at 18:12

21 Answers21

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

console.log( (date.getMinutes()<10?'0':'') + date.getMinutes() );
ogur
  • 4,526
  • 2
  • 17
  • 17
  • 2
    What does this `<10?'0':''` mean? – user1063287 Jun 10 '16 at 11:43
  • @user1063287 it is an inline if else statement – Aryeh Armon Jun 13 '16 at 11:59
  • 5
    @user1063287 It means: "If getMinutes() is less than 10, return a 0, if greater, return an empty string. – Michael Giovanni Pumo Aug 17 '16 at 10:30
  • @user1063287 see here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator – shlgug Feb 21 '19 at 16:11
  • (condition?true:false) in PHP you can omit the true statement (condition?:false) in JS you would then use (condition||false) Ternary operator https://en.wikipedia.org/wiki/Ternary_operation – llange Mar 16 '19 at 09:53
  • Putting this here for a common mistake: if this looks like it doesn't work, you might have missed the brackets surrounding the ternary operators, you'd get weird results without them. DON"T DO THIS: `date.getMinutes() < 10 ? "0" : "" + date.getMinutes()` – xodeeq Mar 08 '23 at 13:31
245

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"
Sirko
  • 72,589
  • 19
  • 149
  • 183
Bambam
  • 3,729
  • 1
  • 16
  • 16
103

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)

Avatar
  • 14,622
  • 9
  • 119
  • 198
  • 2
    Such a great answer – Snsxn Oct 27 '20 at 19:06
  • 2
    Wow! that's the kind of answer i was looking for – Nuvi Dec 07 '20 at 16:54
  • While I really liked this answer, it unfortunately didn't work for me (in Tasker Jslet, for the record). The accepted answer is workaround-ish, but fool-proof! – Melvin Mar 25 '21 at 15:48
  • I don't comment on SO often but I felt compelled to say that this is the correct answer for the issue at hand. For an integer there is no difference between 5 and 05, it only matters when you want to treat the value as a string, in which case using string functions is what you need to do. – bfarber Jul 11 '21 at 19:16
20

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(':');
sf77
  • 631
  • 1
  • 5
  • 6
16

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);
DarckBlezzer
  • 4,578
  • 1
  • 41
  • 51
Hamid Mosalla
  • 3,279
  • 2
  • 28
  • 51
  • 1
    Came here in Nov 2020 and this is the safest answer! – Tim Daubenschütz Nov 10 '20 at 13:35
  • This works for printing out the full timestamp, but if you just want the minutes(or the seconds) by themselves, it won't print 2 digit! If you only include `minute: '2-digit'` in the curly braces, it just prints `3` instead of `03`. Any tips on how to get the `03` just using the `Date` object functions? – Levi Uzodike Oct 14 '22 at 19:10
13

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());
KapteinMarshall
  • 490
  • 6
  • 20
10

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;

user2846569
  • 2,752
  • 2
  • 23
  • 24
7

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.

DarckBlezzer
  • 4,578
  • 1
  • 41
  • 51
Andrew L.
  • 170
  • 2
  • 10
5

Another option:

var dateTime = new Date();
var minutesTwoDigitsWithLeadingZero = ("0" + dateTime.getMinutes()).substr(-2);
IanGSY
  • 3,664
  • 1
  • 22
  • 40
  • I like this solution, but it seems IE8 and earlier versions don't support negative numbers for `substr`. http://www.w3schools.com/jsref/jsref_substr.asp – GtEx Jan 01 '14 at 21:54
5

how about this? it works for me! :)

var d = new Date();
var minutes = d.getMinutes().toString().replace(/^(\d)$/, '0$1');
Yuri M
  • 1,301
  • 1
  • 8
  • 2
4

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

Yaron U.
  • 7,681
  • 3
  • 31
  • 45
3

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
Jordan Papaleo
  • 1,463
  • 11
  • 24
3

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);
DarckBlezzer
  • 4,578
  • 1
  • 41
  • 51
3

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

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
3

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;
}
Glenn
  • 7,262
  • 1
  • 17
  • 23
1

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 !

JRMLSTF
  • 85
  • 9
0
$(".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

0

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

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/

DarckBlezzer
  • 4,578
  • 1
  • 41
  • 51
Younes Ouchala
  • 300
  • 1
  • 4
  • 15
-1

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

z3rone
  • 176
  • 14
  • 1
    This is depreciated - do not use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleFormat – rob_james Jul 25 '18 at 09:30
-4

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.

eso32
  • 45
  • 5