Home > Enterprise >  How to separate date, time and day with title in react native code?
How to separate date, time and day with title in react native code?

Time:06-25

My API Date and Time Format is like this: enter image description here

I'm currently using this method to render the date and time in my code. enter image description here

let d = new Date(item.starts_on);
let date = `${d.getMonth()   1}/${d.getDate()}/${d.getFullYear()}`;
let time = `${d.getHours()}:${d.getMinutes()}`;

But i want to render it in this format enter image description here Pls do help me out

CodePudding user response:

There are two approach for doing it, first way (that is easier) using packages like moment or dayjs by using it you are be able to handle date and convert to many different shapes (for more information check the documents of them). For example if you want to separate date and time from a timestamp you can do it by moment like below:

/*
  other your imports and codes
*/
let timestamp = moment(item.starts_on);
let date = timestamp.format('L');
let time = timestamp.format('LT');
/*
  other your codes
*/

Second way is using at instance of Date, for doing it you can:

/*
  other your imports and codes
*/
let d = new Date(item.starts_on);
let date = `${d.getMonth()   1}/${d.getDate()}/${d.getFullYear()}`;
let time = `${d.getHours()}:${d.getMinutes()}`;
/*
  other your codes
*/

Update Answer For converting date to like "Sat 19 Mar 2022" you want, followings below:

//fill in Months array
const Months = ["Jan", "Feb", ..., "Dec"];
//fill in Days of week array
const Days = ["Sun", "Mon", ..., "Sat"];
/*
  other your codes
*/
let d = new Date(item.starts_on);
let monthIndex = d.getMonth();
let month = Months[monthIndex];
let dayIndex = d.getDay();
let day = Days[dayIndex];

let date = `${day} ${d.getDate()} ${month} ${d.getFullYear()}`;
/*
  other your codes
*/
  • Related