🎁 The Js-Craft Guide to React is now available with a 30% off discount!

Javascript format date no libraries

Formatting dates in vanilla Javascript can be tricky. That's the reason why often of the articles regarding date formatting in JS point to external libraries such as Moment.js or Day.js.

I don't think it's worth adding a few extra kb of Javascript libraries to your page just to do some date formatting.

That's the reason why I've put together this small example that uses the date toLocaleDateString() method to output a Javascript date in different formats:

The supported formats are:

  • YYYY-MM-DD, for example 2023-06-26
  • DD/MM/YYYY, for example 26/06/2023
  • DD MMM YYYY, for example 26, JUN 2023
  • MMMM DD, YYYY, for example June 26, 2023
  • MM/DD/YYYY, for example 06/26/2023

The options parameters of the toLocaleDateString() method does most of the heavy lifting for us:

date.toLocaleDateString('en-US', {
    weekday: 'long', //  values: 'long', 'short', 'narrow'
    year: 'numeric', //  values: 'numeric', '2-digit'
    month: 'short', //  values: 'numeric', '2-digit', 'long', 'short', 'narrow'
    day: 'numeric', //  values: 'numeric', '2-digit'
})

Below is the full code of the example:

// Get the current date
const currentDate = new Date()

// Display the current date in the appropriate container
const cdContainer = document.querySelector('#current-date')
cdContainer.textContent = currentDate

// Get the container for the formatted date
const fdContainer = document.querySelector('#formated-date')

// Listen for changes in the format selection
document.querySelector('#format-select').addEventListener('change', (e) => {
    // Get the selected format
    const newFormat = e.target.value
    // Format the date and display it in the appropriate container
    fdContainer.textContent = formatDate(newFormat, currentDate)
})

// Function to format the date based on the selected format
const formatDate = (format, date) => {
    // Check the selected format and format the date accordingly
    if (format == 'YYYY-MM-DD') {
        const options = { year: 'numeric', month: '2-digit', day: '2-digit'}
        return date.toLocaleDateString('en-GB', options).split('/').reverse().join('-')
    }

    if (format == 'DD MMM YYYY') {
        const options = { day: '2-digit', month: 'short', year: 'numeric' }
        const formattedDate = date.toLocaleDateString('en-US', options)
        const [m, d, y] = formattedDate.split(' ')
        return `${d} ${m.toUpperCase()} ${y}`
    }

    if (format == 'MMMM DD, YYYY') {
        const options = { month: 'long', day: 'numeric', year: 'numeric' }
        return date.toLocaleDateString(undefined, options)
    }

    if (format == 'MM/DD/YYYY') {
        const options = { month: '2-digit', day: '2-digit', year: 'numeric' }
        return date.toLocaleDateString('en-US', options)
    }

    if (format == 'DD/MM/YYYY') {
        return date.toLocaleDateString('en-GB')
    }

    // If the selected format is not valid, display an error message
    return '⛔️ No valid format'
}

The GitHub repo is here, and you can see the live example on GitHub pages.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.


Leave a Reply

Your email address will not be published. Required fields are marked *

📘 The Guide to React Home Screencasts Best of Newsletter Search X

📘 - 10 Javascript AI projects with React and LangChain

Hi friend! Before you go, just wanted to let you know about the 10 Javascript AI projects ideas with React and LangChain FREE ebook.

One of the best ways to learn is by doing the work. Choose from these 10 project ideas and start working on topics such as:

  • How does LangChain work
  • Connecting to OpenAI LLM
  • Create AI Agents
  • Simple and Sequential Chains
  • Adding Memory (Chat Context)
  • Prompt Templates
  • Using OutputParsers and Tools for Agents
  • Work with Documents and more...

Keep building and see the new capabilities LLM models can add to your React app! Get all projects as an ebook right to your inbox!

X