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

1
  • 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 Jul 26, 2013 at 18:12

21 Answers 21

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

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

This solution is cross-browser and cleaner int/string conversion. My advice is to not use a variable named '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"
0
110

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)

2
  • 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, 2021 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, 2021 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(':');
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);

2
  • 1
    Came here in Nov 2020 and this is the safest answer! Nov 10, 2020 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? Oct 14, 2022 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());
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;

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.

6

how about this? it works for me! :)

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

Another option:

var dateTime = new Date();
var minutesTwoDigitsWithLeadingZero = ("0" + dateTime.getMinutes()).substr(-2);
1
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

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

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

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 !

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/

1
  • very nice when one anyways is using moment, thank you :-)
    – seawave_23
    Nov 27, 2019 at 11:35
-1

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.