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.
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.
You can format using date-fns library
const date = "2019-01-02T03:04:05";
format(new Date(date), "do 'of' MMM yyyy"); // 2nd of Jan 2019
Format Options: https://date-fns.org/v2.28.0/docs/format
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'