0

I wanna format the output after getting the values of Date.getHours(), Date.getMinutes() and Date.getSeconds().

Here is the long way:

var dt = new Date();
var HH = dt.getHours();
var mm = dt.getMinutes();
var ss = dt.getSeconds();

HH = HH < 10 ? '0' + HH : HH;
mm = mm < 10 ? '0' + mm : mm;
ss = ss < 10 ? '0' + ss : ss;

My question: How can I compress the last part to .toString('D2') function?

What I wanna archive:

var dt = new Date();
var HH = dt.getHours().toString('D2');
var mm = dt.getMinutes().toString('D2');
var ss = dt.getSeconds().toString('D2');

p/s: .toString('D2') is same meaning with Standard Numeric Format Strings. Like C# syntax:

int i = 1;
Console.WriteLine(i.ToString("D2")); // output: 01
Tân
  • 1
  • 15
  • 56
  • 102
  • 1
    Possible duplicate of [How to output integers with leading zeros in JavaScript](http://stackoverflow.com/questions/2998784/how-to-output-integers-with-leading-zeros-in-javascript) – Gavriel Jan 15 '16 at 06:57
  • You can copy&paste the `printf` for javascript from somewhere. – Tomáš Zato Jan 15 '16 at 07:09

4 Answers4

4

I don't think Javascript has that kind of support. You would need to either write an ancillary function or install a library.

The closest I can think of for a one-liner is

("0"+dt.getSeconds()).slice(-2)

after this answer.

Community
  • 1
  • 1
LSerni
  • 55,617
  • 10
  • 65
  • 107
2

Something like the following should work:

var HH = ('0'+dt.getHours().toString()).slice(-2);

Similar approach for the others.
You can also avoid explicitly calling toString, thus:

var HH = ('0'+dt.getHours()).slice(-2);
skypjack
  • 49,335
  • 19
  • 95
  • 187
  • 1
    you don't need toString, as you already converted it to a string by concatenating to '00'. You also don't need '00', '0' is enough – Gavriel Jan 15 '16 at 07:01
  • I was just writing the first part. You are right about '00', thank you (I've used '00' because it is the desired length, but `getHours` ever returns something actually). – skypjack Jan 15 '16 at 07:02
1
var dt = new Date();
var today = dt.toJSON().slice(0, 10);
var time = dt.toJSON().slice(11, -1);
Jacob Nelson
  • 2,370
  • 23
  • 35
1

This function should be able to provide the solution to your problem. While this is not exactly the way you would like to do it, it is the easiest.

function decimalFormat(precision, number) {
  if (arguments.length !== 2)
    throw new Error("Invalid number of arguments!");
  else if (typeof precision !== "number" || typeof number !== "number")
    throw new TypeError("Invalid parameter type!");
  var zeros = "0";
  for (var i = 0; i < Math.abs(precision); i++)
    zeros += "0";
  return (zeros + number.toString()).slice(-1 * (Math.abs(precision)));
}

alert(decimalFormat(10, 21));
alert(decimalFormat(2, 5221));
alert(decimalFormat(4, 221));
William Callahan
  • 630
  • 7
  • 20