-2

First off i'd like to apologize for the noobish question.

Please take a look at the following code:

var dt = new Date(t*1000);
var m = "0" + dt.getMinutes();

When outputted, it can give us one of the following results, depending of the t variable (aka unix time):

m = 054 // 54 minutes
m = 03 // 3 minutes

As you can see, if theres too many minutes, the formatting becomes broken. To fix this, we must call a function to only keep the two last characters. To do this, we'll use the following code:

var m = "0" + dt.getMinutes();
m = m.substr(-2);

Which can output:

m = 54 // 54 minutes
m = 3  // 03 minutes

Good! We fixed the problem, right? Well, I think that setting the variable two times in a row is stupid. I tried:

var m = "0" + dt.getMinutes().substr(-2);

But I get the following error:

TypeError: dt.getMinutes(...).substr is not a function

Is there a one liner way to do this?

keanu_reeves
  • 350
  • 1
  • 12
  • What im trying to do here is `m = m.functionOne().FunctionTwo();` – keanu_reeves Dec 10 '19 at 03:03
  • You should learn how to get to the heart of a problem, and actually ask about that. You don't need to know how to call two functions in a row - you might need that later but that's irrelevant for this one. Why didn't you simply ask the more basic question 'how do I format a number with a leading zero?' (which is already answered here too) – JK. Dec 10 '19 at 03:07
  • `dt.getMinutes().toString().padStart(2, '0')` – epascarello Dec 10 '19 at 03:09
  • I know how to format a number with a leading zero. I wanted to know how to make it a one-liner, without having to set the variable two times. The answers learn'd me here that I must convert my function's output to a string before I can do string-related stuff to my variables (like only keeping the two last characters) – keanu_reeves Dec 10 '19 at 03:11

1 Answers1

0

Date.getMinutes returns an integer, not a string, so you can't call substr on it. But by adding parentheses around the "0" + dt.getMinutes() expression, you get a string value and you can call substr:

var dt = new Date();
var m = ("0" + dt.getMinutes()).substr(-2);
console.log(m);
Nick
  • 138,499
  • 22
  • 57
  • 95