Strapi date format using javascript

Viewed 2964

I recieve this date format from strapi 2021-09-01T15:21:39.862Z how can i transform it to a DD/MM/YYYY format ?

<div class="post-date-article">{{ formatMyDate(article.published_at) }}</div>

formatMyDate(value){
     if (value) {
       return value;
      }
  }
2 Answers

Strapi are providing a date in ISO 8601 format, which is easy to parse using the JavaScript date object.

I'd suggest using Date.toLocaleDateString() to format the input date as DD/MM/YYYY. Using a locale of 'en-GB' will format the supplied date in this way.

You can pass other locales such as 'de-DE' to format the date in another way if you wish.

function formatMyDate(value, locale = 'en-GB') {
    return new Date(value).toLocaleDateString(locale);
}

const timestamp = '2021-09-01T15:21:39.862Z';
console.log('Timestamp:', timestamp);
console.log('Formatted date:', formatMyDate(timestamp));
.as-console-wrapper { max-height: 100% !important; top: 0; }

This seem to work for me with luxon

import { DateTime } from 'luxon';

...

DateTime.now(post.attributes.createdAt).toFormat('MMMM dd, yyyy')}

or using date-fns (tree shakeable)

import { format, parseISO } from 'date-fns';

...

{format(parseISO(article.attributes.publishedAt), 'MMMM dd, yyyy')}
Related