Home > Blockchain >  Get Day Name from Date in JS
Get Day Name from Date in JS

Time:05-31

enter image description here

Hello guys, i need some help over here, hope that you can provide me the solution.

How can i transform this Date format to a Format that shows the names of the days.

I know that i can use something like this but i dont know how to add that when im mapping data from an object or array.

let getDayName = (dateStr, locale) => {
    let date = new Date(dateStr);
    // console.log(date.toLocaleDateString(locale, { weekday: 'long' }));
    return date.toLocaleDateString(locale, { weekday: 'long' });
  };

 let dateStr = date;

enter image description here

enter image description here

CodePudding user response:

You are on the right track. Only thing missing is, that you need to call your function getDayName() and provide sufficient arguments.

Here an example:

const array = ["2022-05-30 18:00:00", "2022-05-30 17:00:00", "2022-05-25 18:00:00"]

const getDayName = (dateStr, locale) => {
  let date = new Date(dateStr);
  return date.toLocaleDateString(locale, { weekday: 'long' });
};

const output = array.map(dateStr => getDayName(dateStr, "en-GB"))

console.log(output)
.as-console-wrapper { max-height: 100% !important; top: 0; }

In your case you are already mapping using map(), therefore you would just need to call your function within the callback of map():

<!-- other code... -->
<div className="fd-day">
    <h1>{getDayName(item.dt_txt, "en-GB")}</h1>
</div>
<!-- some more code... -->

instead of

<!-- other code... -->
<div className="fd-day">
    <h1>{item.dt_txt}</h1>
</div>
<!-- some more code... -->

Of course you can adjust the locale to whatever fits your needs.

CodePudding user response:

You can add another map declaration and do it there like so:

.filter(() => {})
.map((item) => {
    item.dt_txt = getDayName(item.dt_txt);
    return item;
})
.map(() => {})
  • Related