i'm working in a react project and now I need to show two fields on screen (date and hour) from a database date value.
createdAt: "2021-12-07T00:03:19.474Z"
I need to show the fields like
Date: 07/12/2021
Hour: 03:19
Do you have any idea? Thanks!
CodePudding user response:
You can either explore the Date object and use its methods (such as getHours
, getMinutes
).
const dateFromDB = '2021-12-07T02:22:30.929 00:00';
const date = new Date(dateFromDB);
const day = date.getDate();
const month = date.getMonth();
const year = date.getFullYear();
const hours = date.getHours();
const minutes = date.getMinutes();
console.log(`Date: ${day}/${month}/${year}`);
console.log(`Hour: ${hours}:${minutes}`);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Or, if you can use external libraries / work with dates a lot, use a library that makes this a lot more convenient.