How To Change GetMinutes() To 2 Digit Format In JavaScript

Change getMinutes() to 2 digit format in JavaScript

To change getMinutes() to 2 digit format in JavaScript, we have three methods: use the slice() method, use the padStart() method and create the function to get 2 digits of minutes. Check out the details below to get more information.

Change getMinutes() to 2 digit format in JavaScript

Using the slice() method

The slice() method returns to a new array containing the selected elements. For the getMinutes() method. We already have the article to explain how to use the method here.

Example:

In this example, we create a date string by calling the new Date() method and then using the slice method with -2 to get the rightmost 2 characters of 0 and add to the value getMinutes.

var date = new Date("2012-10-23 16:05:19")
console.log(date)
 
// Using slice method with -2 to get the rightmost 2 characters of 0 to add to value getMinutes
minutes2Digit = ('0'+ date.getMinutes()).slice(-2);

console.log("Get minutes with 2 digit: ", minutes2Digit)

Output

Tue Oct 23 2012 16:05:19 GMT+0700 
Get minutes with 2 digit: 05

Using the padStart() method

Another way to change minutes to 2 digits format is to use the padStart() method. The padStart() method pads the current string with another string until the resulting reaches the given length.

Syntax:

padStart(targetLength, padString)

Parameters: 

  • targetLength: the length of the resulting string.
  • padString: the string to pad the current string with.

Return value: return value is a string.

Example:

var date = new Date("2012-10-23 16:05:19")
console.log(date)
 
// Using padStart method with targetLenght is 2 and padString is 0
minutes2Digit = String(date.getMinutes()).padStart(2, "0");

console.log("Get minutes with 2 digit: ", minutes2Digit)

Output

Tue Oct 23 2012 16:05:19 GMT+0700 
Get minutes with 2 digit: 05

Creating the function to get 2 digits of minutes

The last way to check a value is a number in javascript is creating the function. We will check if the value of minutes is less than 10, then add 0 before it.

Example:

var date = new Date("2012-10-23 16:05:19")
console.log(date)
 
var minutes = date.getMinutes();
console.log("Minutes is: ",minutes)
 
// If getMinutes() is less than 10, return a 0, if greater, return an empty string
minutes2Digit = minutes > 9 ? minutes : '0' + minutes;

console.log("Get minutes with 2 digit: ", minutes2Digit)

Output

Tue Oct 23 2012 16:05:19 GMT+0700 
Minutes is: 5
Get minutes with 2 digit: 05

Summary

In this tutorial, we have explained how to change getMinutes() to 2 digit format in JavaScript by using three methods. We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *