Convert UK date to ISO date in JavaScript

One of the applications I work on captures dates in UK format (dd/mm/yyyy) but needs to convert them into ISO format (yyyy-mm-dd) when making AJAX calls to APIs. Rather than pull in a huge date library just for this simple purpose, I decided to do this in plain/vanilla JavaScript.

const ukDate = '05/01/2022' // or document.querySelector('#my_date).value
const [day, month, year] = ukDate.split('/', 3)
const isoDate = `${year}-${month}-${day}`

The downsides to this approach are that there is no validation and it only converts from one specific format. This was fine for my purposes as it’s part of an internal system and passing the wrong date format to the API would result in an error anyway.

The various bits of syntax, including template literals and const, require ECMAScript 6 (2015). However, browser support for this is well established and you would only run into problems if you had to support Internet Explorer or Opera Mini.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.