How to use the Date object in TypeScript

1 Answer

0 votes
/**
 * Date Object Example in TypeScript
 * ---------------------------------
 * Demonstrates:
 * - Creating Date objects
 * - Reading date parts
 * - Formatting dates
 * - Adding days to a date
 * - Calculating date differences
 * - Using TypeScript type annotations
 */

"use strict";

/**
 * Formats a Date object as YYYY-MM-DD HH:mm:ss
 *
 * @param date Date to format
 * @returns Formatted date string
 */
function formatDate(date: Date): string {
    if (isNaN(date.getTime())) {
        throw new Error("Invalid Date.");
    }

    const year: number = date.getFullYear();
    const month: string = String(date.getMonth() + 1).padStart(2, "0");
    const day: string = String(date.getDate()).padStart(2, "0");

    const hours: string = String(date.getHours()).padStart(2, "0");
    const minutes: string = String(date.getMinutes()).padStart(2, "0");
    const seconds: string = String(date.getSeconds()).padStart(2, "0");

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * Adds a specified number of days to a date.
 *
 * @param date Original date
 * @param days Number of days to add
 * @returns New Date instance
 */
function addDays(date: Date, days: number): Date {
    const result: Date = new Date(date);

    result.setDate(result.getDate() + days);

    return result;
}

/**
 * Calculates the number of days between two dates.
 *
 * @param startDate Starting date
 * @param endDate Ending date
 * @returns Number of days
 */
function getDaysBetween(startDate: Date, endDate: Date): number {
    const millisecondsPerDay: number = 1000 * 60 * 60 * 24;

    const differenceInMs: number =
        endDate.getTime() - startDate.getTime();

    return differenceInMs / millisecondsPerDay;
}

// ------------------------------------------------------------------
// Usage Examples
// ------------------------------------------------------------------

console.log("=== Current Date and Time ===");

// Current date/time
const now: Date = new Date();

console.log(now);
console.log(formatDate(now));

console.log("\n=== Creating Specific Dates ===");

// Create a date from an ISO string
const projectStartDate: Date = new Date("2026-01-15T09:00:00");

console.log(formatDate(projectStartDate));

console.log("\n=== Reading Date Parts ===");

const year: number = projectStartDate.getFullYear();
const month: number = projectStartDate.getMonth() + 1; // Months are 0-based
const day: number = projectStartDate.getDate();

console.log(`Year: ${year}`);
console.log(`Month: ${month}`);
console.log(`Day: ${day}`);

console.log("\n=== Adding Days ===");

const deadline: Date = addDays(projectStartDate, 30);

console.log("Start Date :", formatDate(projectStartDate));
console.log("Deadline   :", formatDate(deadline));

console.log("\n=== Difference Between Dates ===");

const daysBetween: number = getDaysBetween(
    projectStartDate,
    deadline
);

console.log(`Difference: ${daysBetween} days`);

console.log("\n=== ISO Format ===");

// Best format for APIs and databases
const isoDate: string = now.toISOString();

console.log(isoDate);

console.log("\n=== Localized Format ===");

// Best format for display to users
const localizedDate: string = now.toLocaleString("en-US", {
    dateStyle: "full",
    timeStyle: "long"
});

console.log(localizedDate);


/*
run:

=== Current Date and Time ===
2026-10-16T15:18:02.485Z
2026-10-16 15:18:02

=== Creating Specific Dates ===
2026-01-15 09:00:00

=== Reading Date Parts ===
Year: 2026
Month: 1
Day: 15

=== Adding Days ===
Start Date : 2026-01-15 09:00:00
Deadline   : 2026-02-14 09:00:00

=== Difference Between Dates ===
Difference: 30 days

=== ISO Format ===
2026-10-16T15:18:02.485Z

=== Localized Format ===
Friday, October 16, 2026 at 3:18:02 PM UTC

*/

 



answered Oct 16 by avibootz
...