Mastering Date and Time Operations in JavaScript

Creating Date Instances

JavaScript provides the built-in Date object to handle time-related data. Instances can be initialized in several ways depending on the required input.

// Current moment
const now = new Date();

// Specific date string
const scheduledTime = new Date("2023-10-05T14:30:00");

// Less common constructors
const legacyFormat = new Date("Fri Oct 05 2023 14:30:00 GMT+0800");
const yearMonthDay = new Date(2023, 9, 5); // Month is 0-indexed

Extracting Date Components

Once an instance exists, various getter methods retrieve specific units of time. Note that months are zero-indexed (0 represents January).

const moment = new Date();
const info = `Current time: ${moment.getFullYear()}-${moment.getMonth() + 1}-${moment.getDate()} ${moment.getHours()}:${moment.getMinutes()}:${moment.getSeconds()}`;

Key methods include:

  • getTime(): Returns milliseconds since Unix Epoch.
  • getFullYear(): Returns the four-digit year.
  • getMonth(): Returns the month (0-11).
  • getDate(): Returns the day of the month (1-31).
  • getDay(): Returns the day of the week (0-6).
  • getHours(), getMinutes(), getSeconds(): Return respective time units.
  • getMilliseconds(): Returns the milliseconds portion.
const timestamp = moment.getTime();
const year = moment.getFullYear();
const monthIndex = moment.getMonth(); 
const dayOfWeek = moment.getDay();

Relative Date Calculatinos

Calculating dates relative to the current time involves modifying the day value.

// Calculate yesterday
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);

// Calculate N days prior
const daysPrior = (n) => {
    const target = new Date();
    target.setDate(target.getDate() - n);
    return target;
};

// Calculate tomorrow
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

// Calculate N days later
const daysLater = (n) => {
    const target = new Date();
    target.setDate(target.getDate() + n);
    return target;
};

Comparing Dates

To compare dates accurately, convert them to timestamps. String formats should be normalized before parsing.

const inputString = "2023-9-15";
// Normalize separators
const normalized = inputString.replace(/-/g, "/");
const inputTimestamp = Date.parse(normalized);
const currentTimestamp = new Date().getTime();

if (inputTimestamp <= currentTimestamp) {
    console.log("The date is in the past");
} else {
    console.log("The date is in the future");
}

Time Arithmetic

Day of the Year

Calculate which day of the year a specific date represents.

const getDayOfYear = (dateObj) => {
    const startOfYear = new Date(dateObj.getFullYear(), 0, 0);
    const diff = dateObj - startOfYear;
    const oneDay = 1000 * 60 * 60 * 24;
    return Math.floor(diff / oneDay);
};

Adding Time

const addDays = (daysToAdd) => {
    const result = new Date();
    result.setDate(result.getDate() + daysToAdd);
    return result;
};

Calculating Differences

Differences between two dates can be measured in various units by dividing the millisecond difference.

const diffInSeconds = (d1, d2) => (d1 - d2) / 1000;
const diffInMinutes = (d1, d2) => (d1 - d2) / (1000 * 60);
const diffInHours = (d1, d2) => (d1 - d2) / (1000 * 60 * 60);
const diffInDays = (d1, d2) => (d1 - d2) / (1000 * 60 * 60 * 24);

// Difference in months
const diffInMonths = (d1, d2) => {
    const m1 = d1.getFullYear() * 12 + d1.getMonth();
    const m2 = d2.getFullYear() * 12 + d2.getMonth();
    return m1 - m2;
};

Formatting Dates

Extending the prototype allows for custom formatting strings.

Date.prototype.toCustomFormat = function(pattern) {
    const map = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };

    if (/(y+)/.test(pattern)) {
        pattern = pattern.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (const key in map) {
        if (new RegExp("(" + key + ")").test(pattern)) {
            const val = map[key] + "";
            pattern = pattern.replace(RegExp.$1, RegExp.$1.length === 1 ? val : ("00" + val).substr(val.length));
        }
    }
    return pattern;
};

// Usage
const formatted = new Date().toCustomFormat("yyyy-MM-dd HH:mm:ss");

Timestapm to String

const ts = 1696574400000;
const dt = new Date(ts);
const display = `${dt.getFullYear()}年${dt.getMonth() + 1}月${dt.getDate()}日`;

Parsing Strings

const str = "2023-04-16";
const parsed = new Date(Date.parse(str.replace(/-/g, "/")));

Weekday Localization

const resolveWeekday = (dateStr) => {
    const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    const index = new Date(dateStr).getDay();
    return days[index];
};

Practical Formatting Example

const formatDetailed = (dateObj) => {
    const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    return `${dateObj.getMonth() + 1}月${dateObj.getDate()}日 (${weekdays[dateObj.getDay()]})`;
};

Milliseconds to H:M:S

const convertDuration = (ms) => {
    const h = Math.floor(ms / (1000 * 60 * 60));
    const m = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60));
    const s = Math.floor((ms % (1000 * 60)) / 1000);
    
    const pad = (n) => n < 10 ? `0${n}` : n;
    return `${pad(h)}:${pad(m)}:${pad(s)}`;
};

console.log(convertDuration(123456789)); // 34:17:36

Intervals and Timestamps

The Unix timestamp rerpesents milliseconds elapsed since January 1, 1970, UTC.

const epochStart = new Date(0);
// Note: Local timezone offsets may affect display of epoch start
console.log(epochStart.getTime()); 

Converting timestamps back to objects:

const fromTs = new Date(1696574400000);

Calculating intervals:

const startMs = 1491789600000;
const endMs = 1494381600000;
const delta = endMs - startMs;

const daysDiff = delta / (24 * 60 * 60 * 1000);
const hoursDiff = delta / (60 * 60 * 1000);

Libraries

For complex manipulation, libraries like dayjs offer cleaner APIs.

npm install dayjs
import dayjs from 'dayjs';

const getCurrentTime = () => {
    return dayjs().format('YYYY-MM-DD HH:mm:ss');
};

Implementation Examples

Display Current Date

<div id="date-display"></div>
<script>
    const displayDiv = document.getElementById("date-display");
    const now = new Date();
    const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    
    const text = `Today is: ${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} (${weekdays[now.getDay()]})`;
    displayDiv.innerText = text;
</script>

Countdown Timer

<div id="countdown"></div>
<script>
    const targetDiv = document.getElementById("countdown");
    const targetDate = new Date("2024-12-31T23:59:59").getTime();

    const intervalId = setInterval(() => {
        const now = new Date().getTime();
        const distance = targetDate - now;

        if (distance < 0) {
            clearInterval(intervalId);
            targetDiv.innerHTML = "Expired";
            return;
        }

        const d = Math.floor(distance / (1000 * 60 * 60 * 24));
        const h = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const m = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const s = Math.floor((distance % (1000 * 60)) / 1000);

        const pad = (n) => n < 10 ? "0" + n : n;
        targetDiv.innerHTML = `${pad(d)}d ${pad(h)}h ${pad(m)}m ${pad(s)}s`;
    }, 1000);
</script>

Elapsed Time Tracker (Vue 3)

<template>
  <div class="timer">
    {{ formattedElapsed }}
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const elapsedSeconds = ref(0);
const formattedElapsed = ref("00:00:00");
let intervalId = null;

const formatTime = (totalSeconds) => {
    const h = Math.floor(totalSeconds / 3600);
    const m = Math.floor((totalSeconds % 3600) / 60);
    const s = totalSeconds % 60;
    const pad = (n) => n < 10 ? `0${n}` : n;
    return `${pad(h)}:${pad(m)}:${pad(s)}`;
};

onMounted(() => {
    intervalId = setInterval(() => {
        elapsedSeconds.value++;
        formattedElapsed.value = formatTime(elapsedSeconds.value);
    }, 1000);
});

onUnmounted(() => {
    if (intervalId) clearInterval(intervalId);
});
</script>

Digital Clock (Vue 3 + Day.js)

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import dayjs from 'dayjs';

const currentTime = ref('');
let clockInterval = null;

const updateTime = () => {
    currentTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss');
};

onMounted(() => {
    updateTime();
    clockInterval = setInterval(updateTime, 1000);
});

onUnmounted(() => {
    clearInterval(clockInterval);
});
</script>

<template>
  <div class="clock">
    {{ currentTime }}
  </div>
</template>

Tags: javascript date-time web-development programming frontend

Posted on Sat, 18 Jul 2026 17:18:27 +0000 by psyion