# JavaScript: Get minutes with leading zeros

## JavaScript Datetime: Exercise-35 with Solution

Write a JavaScript function to get minutes with leading zeros (00 to 59).

Test Data:
dt = new Date(1989, 10, 1);
"00"

Sample Solution:

JavaScript Code:

``````// Define a JavaScript function called minutes_with_leading_zeros with parameter dt (date)
{
// Check if the minutes value of the provided date is less than 10
// If true, add a leading '0' to the minutes value; otherwise, return the minutes value as is
return (dt.getMinutes() < 10 ? '0' : '') + dt.getMinutes();
}

// Create a new Date object representing the current date
dt = new Date();
// Output the minutes value with leading zeroes for the current date

// Create a new Date object representing November 1, 1989
dt = new Date(1989, 10, 1);
// Output the minutes value with leading zeroes for November 1, 1989
```
```

Output:

```33
00
```

Explanation:

In the exercise above,

• The code defines a JavaScript function named "minutes_with_leading_zeros()" with one parameter "dt", representing a Date object.
• It checks if the minutes value of the provided Date object "dt" is less than 10.
• If the minutes value is less than 10, it adds a leading '0' to the minutes value using a ternary operator (<condition> ? <expression_if_true> : <expression_if_false>).
• If the minutes value is 10 or greater, it returns the minutes value as is.
• The code then demonstrates the usage of the "minutes_with_leading_zeros()" function:
• It creates a new Date object "dt" representing the current date using 'new Date()'.
• It calculates and outputs the minutes value with leading zeroes for the current date by calling the "minutes_with_leading_zeros()" function with "dt" and logging the result to the console.
• It creates another new Date object "dt" representing November 1, 1989, using 'new Date(1989, 10, 1)'.
• It calculates and outputs the minutes value with leading zeroes for November 1, 1989, by calling the "minutes_with_leading_zeros()" function with "dt" and logging the result to the console.

Flowchart:

Live Demo:

See the Pen JavaScript - Get minutes with leading zeros-date-ex-35 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿