What is the method for retrieving the current date based on abbreviated day names?

Within my web service, there is an API that provides information on the days when a shop is available for delivery. The API returns an object containing an ID (which is necessary to obtain hours based on the selected day) and the abbreviated day name (in Italian).

Prior to integrating the API, I had been utilizing the following function to generate an array of days, with 'Today' tagged onto the current day.

  times(maxDays: number, days: ShopDays[]): void {
    const options = { weekday: 'short', day: 'numeric', month: 'short' };
    const today = new Date();
    this.days.push({ // including today in the days array
      formatted: 'Oggi, ' + today.toLocaleString('it-IT', options),
      time: today.toLocaleDateString(),
    });
    for (let i = 0; i < maxDays; i++) { // adding other days based on the maximum days per week variable 'maxDays'
      today.setDate(today.getDate() + 1);
      this.days.push({
        formatted: today.toLocaleDateString('it-IT', options),
        time: today.toLocaleDateString(),
      });
    }
  }

Now that I have access to the API which provides the available days of the week in days.day, I am interested in generating a similar array using the available days from the days array...

This is what the ShopDays[] looks like:

[{id: 1, day: "TUE"}, {id: 2, day: "WED"}, {id: 3, day: "THU"}, {id: 4, day: "FRI"}]

Based on the data returned by the function times(), the resulting array should look something like this:

Today, Wed 23 Sep - Thu 24 Sep - Fri 25 Sep - Tue 29 Sep

If Today is not included, simply display the following days in the array..

Answer №1

To solve this issue, I utilized the moment.js library and specifically leveraged its .isoWeekday function in the following manner:

    moment.locale('it'); // switched to Italian locale for API response compatibility

    const days = ['lun', 'mar', 'mer', 'gio', 'ven', 'sab', 'dom']; // mapped weekdays for reference

    const todayWeekday = moment().isoWeekday(); // set today's weekday index
    const formattedDays = days.map((d) => {
      const dayIndex = days.indexOf(d.day.toLowerCase()); // obtained the index of the day from the object array based on the name
      if (todayWeekday <= dayIndex) { // checked if today's weekday is before or on target day index
        return {
          id: d.id,
          day: moment().isoWeekday(dayIndex),
        };
      } else { // if not, moved to next week and added the day to array
        return {
          id: d.id,
          day: moment()
            .add(1, 'weeks')
            .isoWeekday(dayIndex),
        };
      }
    });

    // sorted the array to have dates in ascending order
    formattedDays.sort((a, b) => moment(a.day).valueOf() - moment(b.day).valueOf());

    // formatted the moment object to obtain a string formatted date
    this.days = formattedDays.map(d => d.day.format('ddd DD MMM'));

    console.log(this.days);

If you have any suggestions for optimizing the efficiency of the code above, feel free to share them!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding functions to the prototype of a function in JavaScript

Is there a more concise way to simplify this code snippet? var controller = function(){ /*--- constructor ---*/ }; controller.prototype.function1 = function(){ //Prototype method1 } controller.prototype.function2 = function(){ //Prototyp ...

The function `open` is not a valid prop for the `Dialog` component

Upon clicking an icon, a dialog box containing a form should appear for either adding a tab or deleting a specific tab. I have utilized reactjs, redux, and material-ui for the components. While I am able to display the dialog box when the icon is clicked, ...

An obstacle encountered when implementing feature module services in a controller for a Nest JS microservice

Recently, I developed a feature module named "user" which includes a controller, model, and services to interact with my postgres database. Despite setting up everything correctly, I encountered an error when trying to call userService from the feature mod ...

Integrating Amazon external images in NextJS

There is a specific issue with loading images from a URL stored on Amazon S3 within the domain configured in next.config.js. Strangely, when using external URLs like Unsplash, the images load fine. The problematic URL is: idinheiro-admin-images.s3.sa-east ...

When utilizing TypeScript's tsc compiler, errors may be generated upon invoking jQuery and Flot code

When I run "make" on x86-64 Linux with this code (a branch of a GitHub repository), I encounter the following errors: shlomif@telaviv1:~/Download/unpack/to-del/TypeScript-flot$ make tsc --outFile foo.js foo.ts foo.ts(18,12): error ...

How can I modify the jQuery aToolTip plugin to enable tooltips on images, fields, and spans in addition to links?

I am facing an issue with my current tooltip setup where they only work on the titles of links and not on images, fields, or spans. How can I make the tooltips work on all titles? Below is the aToolTip JS code: (function($) { // jQuery plugin code fo ...

Adding new data to an object of objects can be a complex task, especially when the new data is coming from a state variable in React that is also an

I'm currently working on populating an object of objects with new data that is being stored in a state variable in React, which is also an object. Here's the code snippet I have: let userData = { harsh:{ password:"harsh", ema ...

Utilizing custom validity for asynchronous validation of forms

I am implementing a feature where users can only submit the form if the user does not already exist. To achieve this, I have created a custom rest API to check if the entered user already exists either on input blur or form submission. This approach has be ...

ionRangeSlider adjusts values according to a given percentage

I am currently utilizing the ionRangeSlider library for my project. My goal is to synchronize 2 sliders based on their current percentage. Below is the code I have implemented: $(function(){ $("#foo").ionRangeSlider({ type: "single", grid: t ...

Encountering a 400 error while using Stripe CLI to listen for webhooks on localhost

Good day everyone! I've been encountering a 400 error when trying to listen to stripewebhooks. The command I'm using is: stripe listen --forward-to localhost:3000/stripe/webhooks After a successful payment: 2024-02-11 19:03:48 --> charge.suc ...

Can you provide some guidance on accessing HTTP headers while using Promises to make AJAX requests?

Currently, I am working on resolving jQuery ajax requests using bluebird.js and I have found it quite challenging to access the HTTP headers of the request. Here is a snippet of the code I am working with: Promise.resolve($.get(...)).then(function(data){ ...

Error: The function registerUser from require(...) is not defined

I am facing an issue where I am trying to import the registerUser function inside router.post within the same file that houses its exported function (registerUser). However, when attempting to use it outside of this module, I receive the following error: ...

Leveraging data from a REST API response in Angular to populate a table?

I have a specific JSON structure that was included in the template I'm currently using: $scope.details = [ { name: 'jim' age: '21' }, { name: 'mike'; age: '60' } ...

The AutoComplete feature of MaterialUI Component fails to function properly even when there is available data

I am facing an issue with my component as it is not displaying the autosuggestions correctly. Despite having data available and passing it to the component through the suggestions prop while utilizing the Material UI AutoComplete component feature here, I ...

Ways to eliminate the initial digit of a decimal number if it is less than 1

I need assistance with modifying float values by removing the first number if it's lower than 1 In the "OPS" table section, I am calculating the sum of OBP and SLG obtained from a database. https://i.sstatic.net/cYwwW.jpg See the code snippet below ...

Attempting to relocate the product section beneath the category sections within the sidebar of x-cart 5

Check out this website link: I attempted to rearrange the best seller product section below the category section in the sidebar. I enabled Layout editor mode from the admin end, dragged the best seller products below the category sections, and saved it. I ...

Placing a cookie prior to the page being refreshed or closed

Once again, I find myself turning to the SO community for assistance. I'm currently in the process of modifying a Joomla "quiz" component to meet my specific needs. My current goal is to alter the "refresh" behavior of the component. Essentially, eac ...

Revamping the static method signature of a class in Typescript

One of the modules I'm using is called some-module and it defines a class like this: export declare class Some<T> { ... static create<T>(): Some<T>; map<U>(x: U): Some<U>; } export default Some In my project, I ...

A plethora of color choices in a Multi-select Box

Hi there! I am facing an issue with dynamically adding multiple select boxes. Currently, I have 4 color-coded options under the selection boxes, which work fine when there is only one box. However, when I add more than one select box, the color coding doe ...

After a successful login, Angular will once again redirect the user to the login page

I successfully implemented the back-end using nest-js to handle authentication with mongo-db. Registration and login are working fine, but I face an issue after logging in with a successful result - when I refresh the page, it redirects me back to the logi ...