dilkhush-raj
Code snippets

Format Date function

Format date utils code written in TypeScript.

Introduction

Date formatting is a common task in web development. It involves converting a date object into a human-readable string. This utility function is a simple implementation of this functionality.

export function formatDate(dateInput: Date | string | number) {
    const date = new Date(dateInput);
 
    if (isNaN(date.getTime())) {
        console.error("Invalid date provided to formatDate:", dateInput);
        return "";
    }
 
    const day = date.getDate().toString().padStart(2, "0");
    const monthNames = [
        "Jan",
        "Feb",
        "Mar",
        "Apr",
        "May",
        "Jun",
        "Jul",
        "Aug",
        "Sep",
        "Oct",
        "Nov",
        "Dec",
    ];
    const month = monthNames[date.getMonth()];
    const year = date.getFullYear();
 
    return `${day} ${month} ${year}`;
}

On this page