Working with Math and Date

Learn common uses of JavaScript Math and Date through practical examples for front-end beginners.

🎯 Introduction

Use Math to perform calculations such as rounding and generating random numbers. Use Date to retrieve dates and times and format them for display.


🔢 Math Basics and Practical Examples

JavaScript’s built-in Math object provides mathematical constants and functions. It is useful for everyday tasks such as rounding numbers, finding minimum and maximum values, and generating random numbers.

Common Math Methods

  • Math.round(x): Round to the nearest integer.
  • Math.floor(x): Round down, for example 2.9 -> 2.
  • Math.ceil(x): Round up, for example 2.1 -> 3.
  • Math.random(): Generate a random decimal from 0 (inclusive) to 1 (exclusive).
  • Math.max(a, b, c, ...) and Math.min(a, b, c, ...): Find the maximum and minimum values.
Math.random() produces pseudorandom numbers. Results vary across page loads, making it suitable for simple random effects.

Example 1: Generate a Random Integer from 1 to 100

<style>
    .example {
        margin: 10px 0;
        font-size: 16px;
    }
</style>

<div class="example" id="randomNumber"></div>

<script>
    function getRandomInt(min, max) {
        // Scale a random value from 0 to 1 by the range size, add the minimum, and round down
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    document.getElementById('randomNumber').textContent =
        'Random number (1–100): ' + getRandomInt(1, 100);
</script>

The getRandomInt function can generate integers within any given range. This is useful in front-end games, prize draws, pagination, and similar tasks.

Example 2: Find the Maximum and Minimum Values in an Array

<style>
    .example {
        margin: 10px 0;
        font-size: 16px;
    }
</style>
<div class="example" id="maxMin"></div>

<script>
    const numbers = [10, 23, 45, 2, 78, 34];
    const max = Math.max(...numbers);
    const min = Math.min(...numbers);

    document.getElementById('maxMin').textContent = `The maximum is ${max} and the minimum is ${min}`;
</script>

This example briefly uses the ES6 spread syntax ... to pass the array elements as separate arguments to Math.max and Math.min.


⏰ Date Basics and Practical Examples

JavaScript’s Date object handles dates and times. Common tasks include displaying the current time, calculating time differences, and formatting dates.

Creating Date Objects

  • new Date(): Create a date object for the current time.
  • new Date('2024-06-01'): Create a date object from a date string.
  • new Date(timestamp): Create a date object from a timestamp.

Methods for Reading Date Values

  • getFullYear(): Get the four-digit year.
  • getMonth(): Get the month (0–11, where 0 is January).
  • getDate(): Get the day of the month.
  • getHours(), getMinutes(), getSeconds(): Get the hours, minutes, and seconds.
Months are zero-based in Date, so add 1 when displaying the month as a conventional month number.

Example 3: Display the Current Time as YYYY-MM-DD HH:mm:ss

<style>
    .example {
        margin: 10px 0;
        font-size: 16px;
    }
</style>
<div class="example" id="currentTime"></div>

<script>
    function formatDate(date) {
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();

        // Pad single-digit values with a leading zero
        const padZero = num => (num < 10 ? '0' + num : num);

        return (
            `${year}-${padZero(month)}-${padZero(day)} ` +
            `${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`
        );
    }

    const now = new Date();
    document.getElementById('currentTime').textContent = 'Current time: ' + formatDate(now);
</script>

Example 4: Calculate the Difference Between Two Dates in Days

<style>
    .example {
        margin: 10px 0;
        font-size: 16px;
    }
</style>
<div class="example" id="dateDiff"></div>

<script>
    const date1 = new Date('2024-06-01');
    const date2 = new Date('2024-06-10');

    // Calculate the difference in milliseconds
    const diffTime = date2.getTime() - date1.getTime();
    // 1 day = 24 * 60 * 60 * 1000 milliseconds
    const diffDays = diffTime / (1000 * 60 * 60 * 24);

    document.getElementById('dateDiff').textContent = `The dates are ${diffDays} days apart`;
</script>

❓ Knowledge Check

Q1: Can Math.random() return 1? No. Its range includes 0 but excludes 1.

Q2: Why add 1 to the month from a Date object? JavaScript numbers months from 0, with 0 representing January, so add 1 for display.

Q3: How do you calculate the number of days between two dates? Get their timestamps with getTime(), subtract them, and divide by the number of milliseconds in a day.


🧪 Exercises

Exercise 1: Use Math to Generate a Random Color (such as #a1b2c3)

<style>
    .color-box {
        width: 100px;
        height: 100px;
        border: 1px solid #ccc;
        margin-top: 10px;
    }
</style>
<div>
    <button id="colorBtn">Generate a random color</button>
    <div class="color-box" id="colorBox"></div>
</div>

<script>
    // Complete this function to generate a random hexadecimal color on click and apply it to colorBox
    function getRandomColor() {
        // TODO: Generate a random color
    }

    document.getElementById('colorBtn').onclick = function () {
        const color = getRandomColor();
        document.getElementById('colorBox').style.backgroundColor = color;
    };
</script>

Exercise 2: Use Date to Count Down the Days, Hours, and Minutes to a Future Date

<div id="countdown"></div>

<script>
    // Write a function that displays the days, hours, and minutes until 2024-12-31 00:00:00 in countdown
    function countdown() {
        // TODO: Implement the countdown
    }

    setInterval(countdown, 1000); // Update every second
</script>

🎉 You now know how to round numbers, generate random values with Math, and work with dates and times using Date. Keep practicing these essential front-end skills!