How to format dates in JavaScript specifically?

Viewed 82

I have a date in the following format 2019-01-02T03:04:05 and I would like to convert and display it in the UI like this: 3rd of Jan 2019. I am not quite sure what format is called and how to convert them into the desired format like this: 3rd of Jan 2019.

Does anybody know how to achieve this? I am using JavaScript and React for handling this logic.

4 Answers

For formatting dates - it is easier (and is a best practice as well) to use a library, like moment.js or similar.

moment('your date here').format('output format here (read moment.js docs and see an examles)');

moment().format('MMMM Do YYYY, h:mm:ss a');  // June 13th 2022, 10:26:03 am

For your case:

moment('2019-01-02T03:04:05').format('Do [of] MMM YYYY'); // 2nd of Jan 2019

you have the 2nd of Jan, not the 3rd of Jan.

I agree with @Sergej.

For formatting dates - it is easier (and is a best practice as well) to use a library, like moment.js or similar.

But if you would like to create your own functions, I think you could use this.

function formatDate(date) {
    const d = new Date(date);
    const day = d.getDate();
    const month = d.toLocaleString('default', { month: 'short' });
    const year = d.getFullYear();
    return `${ordinal(day)} of ${month} ${year}`;
}

function ordinal(day) {
    const suffixes = ['th', 'st', 'nd', 'rd'];
    const mod100 = day % 100;
    const suffix = (mod100 >= 11 && mod100 <= 13) ? 'th' : suffixes[(day % 10 < 4) ? (day % 10) : 0];
    return `${day}${suffix}`;
}

console.log(formatDate("2019-01-02T03:04:05")) //Output: '2nd of Jan 2019'

You can use Day.js ==> Fast 2kB alternative to Moment.js with the same modern API

Code:

const dates = [
  '2019-01-01T03:04:05',
  '2019-01-02T03:04:05',
  '2019-01-03T03:04:05',
  '2019-01-04T03:04:05',
  '2019-01-05T03:04:05',
  '2019-01-30T03:04:05',
  '2019-01-31T03:04:05'
]
const datesFormated = dates.map(d => dayjs(d).format('Do [of] MMM YYYY'))

console.log(datesFormated)
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.3/dayjs.min.js" integrity="sha512-Ot7ArUEhJDU0cwoBNNnWe487kjL5wAOsIYig8llY/l0P2TUFwgsAHVmrZMHsT8NGo+HwkjTJsNErS6QqIkBxDw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.3/plugin/advancedFormat.min.js" integrity="sha512-MGC6Za7V8BU0nL3GVjgssHGIZkIMM6A+tcnxqwkdDASdOnyHwmCwyoVfxSYDxiznl4DDYeZP0Jn0p5MW+r4Rnw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>dayjs.extend(window.dayjs_plugin_advancedFormat)</script>

Related