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.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X