Home > front end >  Generating 7 days in a week as formatted object
Generating 7 days in a week as formatted object

Time:12-28

so I am using the momentJS library as the moment to create an array of 7 days in a week like this:

const moment = require('moment')
var startOfWeek = moment().startOf('week');
var endOfWeek = moment().endOf('week');

var days = [];
var day = startOfWeek;

while (day <= endOfWeek) {
    days.push(day.format("MMMM ddd DD, YYYY "));
    day = day.clone().add(1, 'd');
}

console.log(days);

And the result return an array of 7 days a week like this:

["December Sun 25, 2022 ","December Mon 26, 2022 ", "December Tue 27, 2022 " , "December Wed 28, 2022 ", "December Thu 29, 2022 ", "December Fri 30, 2022 ", "December Sat 31, 2022 "]

But the result that I look for is something like this:

const weekday = [
  {
    day: Mon,
    date: 26 
  },
  {
    day: Tue,
    date: 27 
  },
  {
    day: Wed,
    date: 28 
  },
  {
    day: Thu,
    date: 26 
  },
  {
    day: Fri,
    date: 26 
  },
  {
    day: Sat,
    date: 26 
  },
]

I am stuck on how to convert the data, could anyone able to help me ? Thanks

CodePudding user response:

Without momentjs, you can use toLocaleDateString and other native Date methods to achieve the result:

const day = new Date();  // Today
day.setDate(day.getDate() - day.getDay() - 1);  // Most recent Saturday (not today)
const weekday = Array.from({length: 7}, () => (
    day.setDate(day.getDate()   1), {
        day: day.toLocaleDateString("en-US", { weekday: "short" }),
        date: day.getDate(),
    }
));

console.log(weekday);

CodePudding user response:

If you wish to keep the original output to use elsewhere and not modify the original code, you can map over the days array and construct a new array based on the formatted string (converting to an integer as necessary).

const days = ["December Sun 25, 2022 ", "December Mon 26, 2022 ", "December Tue 27, 2022 ", "December Wed 28, 2022 ", "December Thu 29, 2022 ", "December Fri 30, 2022 ", "December Sat 31, 2022 "]

const weekday = days.map((formattedDate) => {
  const [_, day, dateString] = formattedDate.split(" ");
  return {
    day,
    date: parseInt(dateString)
  };
});

console.log(weekday);

Alternatively, you can modify your original code

//const moment = require('moment')
const startOfWeek = moment().startOf('week');
const endOfWeek = moment().endOf('week');

// uncomment if you still want `days`
// const days = [];
const weekday = [];
let day = startOfWeek;

while (day <= endOfWeek) {
    // days.push(day.format("MMMM ddd DD, YYYY "));
    weekday.push({ day: day.format("ddd"), date: day.date() });
    day = day.clone().add(1, 'd');
}

console.log(weekday);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

  • Related