This method is able to add a leading character to the start of the string, such as a zero character or a space. You can find its syntax and usage here.
We already know that the second part has a maximum length of 2 because it is always smaller than 60, so we should have set 2 as the length argument of this method:
let date = new Date('November 11, 2011 11:11:01') // Change getSeconds() to 2 digit format let second = date.getSeconds().toString().padStart(2, '0') console.log(second)
However, this method is not working in the Internet Explorer browser. If you want to overcome this limit, you can read the next approach instead.
Using the if statement
let date = new Date('November 11, 2011 11:11:01') // Change getSeconds() to 2 digit format let second = date.getSeconds() if (second < 10) second = '0'+ second; console.log(second)
The logic behind this method is very simple to understand. Because if the second part is smaller than 10, it will appear in 1-digit format; therefore, we need to concatenate it with a zero character. Otherwise, the second contains two digits already because it is smaller than 60 and greater than (or equal to) 10.
Using the ternary operator
This ternary operator is really simple to use, and it takes three operands that are: a guard condition put before a question (?), then a statement to run in case the condition is correct. After that is a colon (:) and the final expression to apply when the condition is not truthy. As can be seen, it works exactly like the if-else statement instead of an if statement. For example:
let date = new Date('November 11, 2011 11:11:01') // Change getSeconds() to 2 digit format let seconds = date.toLocaleTimeString(,options) seconds = (seconds < 10)?"0"+seconds :seconds console.log(seconds)
As you can see, the result of this approach is the same as the two others. Because if the second in the time is smaller than 10, it appears in 1-digit format, we have to append it with a character ‘0’ so that we can get seconds to 2-digit format. Otherwise, the second will already be in 2-digit format, so we should print it out instead of adjusting it.
Name of the university: HCMUT