What is the best way to find the beginning and end of the week using Moment.js?

Is there a way to retrieve the date of the first day of the week and the date of the last day of the week using Moment.js?

I am looking to fetch the dates from the start of the week until the end of the current week based on the current day in Moment.js.

Although I came across the weekday() function in the documentation at https://momentjs.com/docs/, I still need assistance in obtaining the first and last days of the week according to the current date using Moment.js. How can I achieve this?

This information is required for data filtering in an Observable based on different time periods such as Month, Week, etc.

var start_date = moment(this.start_date, 'DD/MM/YYYY').format('YYYY-MM-DD')
var final_date = moment(this.final_date, 'DD/MM/YYYY').format('YYYY-MM-DD')

this.transacoesList = this.transacoesList
  .filter((v) => {

    var release_date = moment(v.release_date, 'DD-MM-YYYY').format('YYYY-MM-DD');

    if (moment(release_date).isBetween(start_date, final_date, null, '[]')) {
      return true;
    }
  });

Answer №1

You're heading in the right direction. By utilizing the weekday function, you can easily obtain the dates for Monday and Friday of the current week.

var now = moment();
var monday = now.clone().weekday(1);
var friday = now.clone().weekday(5);
var isNowWeekday = now.isBetween(monday, friday, null, '[]');

console.log(`Current time: ${now}`);
console.log(`Monday: ${monday}`);
console.log(`Friday: ${friday}`);
console.log(`Is it currently between Monday and Friday: ${isNowWeekday}`);

To learn more about the weekday function in Moment.js, refer to the official documentation here: https://momentjs.com/docs/#/get-set/weekday/

Answer №2

Obtaining the start and end dates of the current week can be achieved with the following code:

let currentDate = moment();
let weekStart = currentDate.clone().startOf('week');
let weekEnd = currentDate.clone().endOf('week');

You can then format it like this:

let formatted = weekEnd.format('YYYY-MM-DD');

By the way, I suggest using Luxon instead of moment for various reasons, with immutability being one of the key advantages.

Answer №3

When using Moment's weekday function, if the return value is 0 for today's date, that means it is the first day of the week in your locale. In this case, you are already at the beginning of the week. If the weekday value is not 0, you can simply subtract that number of days from the current date using Moment's date manipulation functions to find the first day of the week.

Once you have identified the first day of the week, you can add 6 days to that date to determine the last day of the week.

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

The setLanguage function in jsPDF does not support rendering different language characters

I'm currently working with jsPDF in Angular 2 and I'm experiencing an issue where my HTML content is not converting successfully into a PDF when it's written in Hebrew. Other languages seem to work fine, but Hebrew is causing a problem. How ...

Sample Angular component showcasing arguments and content within a storybook MDX preview

We showcase our angular components using Storybook and typically utilize the MDX format for this purpose When dealing with an angular component that needs content and accepts properties (via the "Controls" Plugin), I am facing difficulties in implementing ...

Having trouble with obtaining real-time text translation using ngx translate/core in Angular 2 with Typescript

Issue : I am facing a challenge with fetching dynamic text from a JSON file and translating it using the translate.get() method in Angular2. this.translate.get('keyInJson').subscribe(res => { this.valueFromJson = res; /* cre ...

Once I introduce ngModel into mat-checkbox, the functionality of 'checked' stops working

When I add an ngModel to my mat-checkbox, the checked = "checked" functionality stops working as expected. The following code will work: <mat-checkbox name="BlackBeard" ngModel checked = "checked"> Zehahaha? </mat-checkbox> However, the foll ...

Interacting Between Module Components in Angular 2

I have a situation where I have one component that needs to pass data to another component located in a different module. The app.component acts as the parent of these child modules. However, they are only connected through routing, so they are not technic ...

Working with intricately structured objects using TypeScript

Trying to utilize VS Code for assistance when typing an object with predefined types. An example of a dish object could be: { "id": "dish01", "title": "SALMON CRUNCH", "price": 120, ...

Issue: Unable to locate the module 'nexmo' & error TS2307: 'nexmo' module not found

Currently, I am utilizing the powerful NestJs Framework alongside typescript. My task involves incorporating two-factor authentication (SMS) using the Nexmo node library. You can find further information on their website: During the development phase, ev ...

Issue: Unable to resolve all parameters for TypeDecorator in Angular 2 RC-6

I've been struggling with this error for more than a day, and I can't seem to figure out the cause. app.module import {NgModule} from "@angular/core"; import {BrowserModule} from "@angular/platform-browser"; import {AppComponent} from "./app.co ...

Any tips on silencing webpack's constant nagging about the "Critical dependency: require function is used in a way..." warning message?

My immediate goal is to resolve this warning. However, it seems that a different approach may be necessary. I have developed an npm library for date/time functions with most of the code being general-purpose and compatible with both Node.js and web browse ...

Uploading files into an array using Angular 2

Struggling to incorporate an uploader within an array: I've got an array of users displayed in a table using "ng-repeat". I want to add a column with a button to upload an image for each user. Currently, I'm utilizing ng2-file-upload, but open t ...

An effective way to define the type of a string property in a React component using Typescript

One of the challenges I'm facing is related to a React component that acts as an abstraction for text fields. <TextField label="Enter your user name" dataSource={vm} propertyName="username" disabled={vm.isSaving} /> In this set ...

Creating a Vue 3 Typescript project may lead to encountering the error message "this is undefined"

Just diving into Vue using Vite and TypeScript for my project, but running into errors during the build process. Most of them are Object is possibly 'undefined', particularly in parts of my template like this: <input :value="this.$store.s ...

Purging the localStorage upon the initialization of an Angular application

I have a project in Angular where I need to clear the localStorage when the user first opens the application, ensuring that it is cleared automatically if the browser or tab is closed. In addition, I want to redirect the user to the login component upon ...

In Angular 2, transferring data from a parent route to a child route

I have set up a route named "home" with three child routes: documents, mail, and trash. Within the home route component, there is a variable called 'user'. While I am familiar with various methods of passing information between parent and child c ...

Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows. https://i.stack.imgur.com/3haZW.png Current Behavior: Uploadi ...

Angular Universal causes SASS imports to malfunction

Check out this sample app that you can download to see the issue in action: https://github.com/chrillewoodz/ng-boilerplate/tree/universal I am currently working on implementing angular universal, but I'm encountering an error with a SCSS import in o ...

Excluding node modules from Webpack TerserPlugin

I am currently working on a custom Angular Builder and I need to exclude an entire module from the minification/optimization process. According to the Webpack .md file: exclude Type: String|RegExp|Array Default: undefined This setting is used to spe ...

Using JavaScript to define an array of objects

My issue lies with transforming a JSON structure like the one below: [{ "groupid": 29, "percentage": 14 }, { "groupid": 29, "percentage": 22 }, { "groupid": 59, "percentage": 66, }] I am looking to convert it into the format shown ...

How can we effectively divide NGXS state into manageable sections while still allowing them to interact seamlessly with one another?

Background of the inquiry: I am in the process of developing a web assistant for the popular party game Mafia, and my objective is to store each individual game using NGXS. The GitLab repository for this project can be found here. The game includes the f ...

There seems to be an issue in Angular as it is unable to retrieve /

I'm encountering an issue with my simple application where I am receiving the error message "Cannot GET /." Also, in the console, I see this error: TypeError: Cannot read property 'checked' of null at Object.SL_BBL_locer. I'm unsure ab ...