Utilize moment.js to filter an array of objects based on 'last month' and 'last week' when clicked

In my database, each object has a dateCreated value of 2015-12-11T11:12:14.635Z

I'm trying to filter this array for the past week and month.

The issue is that if today is March 19th, I want to search from the 11th to the 18th for the last 7 days, starting at 00:00:01 each day.

First, I need to calculate the past week using moment.js based on the current date and then convert it to the required format for filtering data.

In essence, I am looking to determine the dates for the previous week using the current timestamp.

Answer №1

Ensure the following date configurations:

var last7DayStart = moment().startOf('day').subtract(1,'week');
var lastMonthThisDay = moment().startOf('day').subtract(1,'month');
var yesterdayEndOfRange =  moment().endOf('day').subtract(1,'day');

If dealing with a javascript filter, consider using lodash. Here's an example:

var javascriptArrayOfObjectsWithDates = [
          { date : '2015-12-11T11:12:14.635Z', anotherProperty: 0 },
          { date : moment().subtract(1, 'day' ).format(), testThis: 'works!'}
        ];

var filteredObjects = _.filter(javascriptArrayOfObjectsWithDates,     
                       function(each){ 
                          return moment(each.date)
                            .isBetween(last7DayStart, yesterdayEndOfRange) ;
                       });

Answer №2

This method worked perfectly for me:

_this.lastWeek = function () {
  var result = moment().subtract(7,'days').hours(0);   
  return result._d;
};

_this.lastMonth = function () {
  var result = moment().subtract(30,'days').hours(0);   
  return result._d;
};

Next, I used underscoreJS to filter my array (loadash can also be used):

_this.thisWeekData = _.filter(_this.inbox, function(inbox) {
    return (moment(inbox.createdAt) > _this.lastWeek());
});

_this.lastWeekData = _.filter(_this.inbox, function(inbox) {
    return ((moment(inbox.createdAt) < _this.lastWeek()) && (moment(inbox.createdAt) > _this.lastMonth()));
});

_this.lastMonthData = _.filter(_this.inbox, function(inbox) {
    return (moment(inbox.createdAt) < _this.lastMonth());
});

If you prefer not to handle this logic in your controller, consider using the "Angular-filter" library directly in HTML.

You can find the angular-filter library here

Thank you all for your support!

Answer №3

If you want to go back in time to exactly 7 days ago at midnight, use the following code:

let sevenDaysAgo = moment().subtract(7,'days').startOf('day');

let thirtyDaysAgo = moment().subtract(30,'days').startOf('day');

From there, you can format the date and time however you prefer. For example, to convert it to a Unix timestamp in milliseconds:

let sevenDaysAgoMilliseconds = sevenDaysAgo.format('x');

Now you can easily compare these timestamps for your needs.

Answer №4

My method of categorizing by time periods:

  1. Today
  2. Last 7 Days (Including Last Week)
  3. Last 30 Days (Including Last Month)
const today = moment();
const lastSevenDays = moment().subtract(7, 'days');
const lastThirtyDays = moment().subtract(30, 'days');

const FILTER_MAP = {
  All: () => true,
  Today: task => task.timestamp.isBetween(today, today, 'day', '[]'), // [] denotes inclusive
  Week: task => task.timestamp.isBetween(lastSevenDays, today, 'day', '[]'),
  Month: task => task.timestamp.isBetween(lastThirtyDays, today, 'day', '[]'),
};

const DATA = [
  { id: "0", name: "Eat", timestamp: moment().subtract(6, 'days') },
  { id: "1", name: "Sleep", timestamp: moment() },
  { id: "2", name: "Pawn", timestamp: moment().subtract(28, 'days') },
  { id: "3", name: "Repeat", timestamp: moment().add(1, 'days') } // for testing purposes + 1 day
];

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

Locate the hyperlink within a div using JavaScript and navigate to it

I stumbled upon an element (div1) and now I am looking for a link within that element (link) so that I can navigate to it. <div class="div1"> <p> <a href="link">Link</a> </p> </div> ...

Updating the state of a disabled field in a React component

I have been trying to display a default value and disable the field. The values are successfully displayed but the state is not getting updated. Can someone please guide me on how to update the state of a disabled field? I have put in a lot of effort but h ...

React - manipulating data with state, yay or nay?

My form has two columns - the left column displays a proposed value for the right column. Currently, I retrieve both values from separate API calls and everything is functioning as expected. This is how my code looks at the moment: const dbContact = useD ...

Difficulty reloading after updating input using AngularJS ngTable

I'm encountering an issue where I need to utilize ngTable with TableParams to load and modify a table. For instance, when the page initializes, entering a number in the textbox for the first time displays the appropriate number of rows in the table. ...

Error encountered: MongoDB cast exception - nested subdocument

Check out this schema design: var messageSchema = new Schema({ receivers: [User], message: String, owner: { type: Schema.Types.ObjectId, ref: 'User' } }); var userSchema = new Schema({ name: String, photo: String }); var in ...

Trouble Encountered with AngularJS ng-bind-html and Text not Wr

I am facing an issue with a table cell containing very lengthy text. While the text displays properly in edit mode, it overflows and does not adhere to the width of the cell when not in edit mode. I even tried removing it from ng-bind-html, but the problem ...

Buttons in Highcharts

Is there a way to incorporate a button within a highcharts graph? I am working with a bar chart and would like to include a button on the left side of the label, similar to the example shown in this bar chart demo. I want the button to appear before the ...

Switching background images dynamically depending on the screen size: CSS and HTML5 Gallery

Here's the issue: the HTML5 page is responsive, but the background images are not changing with the screen size. The current code looks like this: <div id="home-gallery" class="gallery-container fullscreen"> <section id="home-welcome" class= ...

Issue encountered during rendering: The function used is not a filter

Everything works fine with the search filter and pagination on the initial load. However, upon clicking to go to the next page, an error occurs stating **'Error in render: "TypeError: this.tickets.filter is not a function"'**. This issue can b ...

Check if the path meets the criteria to be considered valid JavaScript code

I have a javascript variable containing a path that may point to an image file, like ../app/assets/icon.png. If the path is incorrect or doesn't exist, I need to use a different file from another location. The final code should resemble this: var ver ...

The find function is malfunctioning in React

My goal is to have my code send specific username strings to the Profile page using the username props retrieved through the find() method and store the result in a function named user. However, I'm facing an issue where the find method doesn't c ...

jQuery Issue - Clash between multiple menus sharing the same class

Hey there! I'm currently diving into the world of jQuery and encountering an issue with my menu. Whenever I click on a menu item with either the "tm-nav-vertical" or "tm-nav-horizontal" class, it removes the .active class from the initial menu item. I ...

Implement a mouseenter event to all input elements that have specific names stored in an array, utilizing jQuery

I'm struggling to figure out how to apply my function to all input elements with a name that is included in my array. This is what I've attempted so far: var names = ["name1", "name2"]; $(document).ready(function(){ $('input[name=names[ ...

What is the reason behind shadow dom concealing HTML elements when viewed in inspect mode?

https://i.stack.imgur.com/UZM7f.png Monday.com has implemented Shadow Dom to protect its source code. How can I work around this limitation? ...

Angular-UI's global modals: the key to international success

I'm curious if it's possible to streamline the process of invoking modals by moving the code outside of each document and instead accessing them from a common factory. Currently, I trigger dialogs like this: vm.showObjectInfo = function () { ...

Opening the Gmail app from a link using JavaScript

What is the best way to open the Gmail app from a hyperlink? This link opens WhatsApp <a href="https://wa.me/">whatsapp</a> <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a1f190f ...

How to toggle a boolean variable in AngularJS when transitioning between states

Just getting started with AngularJS and trying to figure out how to tackle this issue. I have set up the following route: name: "Tracker", url: "/tracker/:period", and I have 3 distinct states for which I've created 3 separate functions to facilit ...

Tips for altering the label color of an md-input-container after text has been entered

Is there a way to dynamically change the color of an md-input-container label after certain input is added? The default grey color gives the impression that the field is disabled. I specifically want to modify the color of the label "Description" when the ...

Utilizing a plugin to execute a function in Wordpress

I'm currently facing the challenge of combining two WordPress plugins without the need to modify one to fit into the other seamlessly. My main question is: How can I call a function from one plugin that exists outside of another plugin? For example, ...

Switching an element from li to div and vice versa using Jquery Drag and Drop

I am currently experimenting with the following: Stage 1: Making the element draggable from li to div upon dropping into #canvas Placing the draggable element inside #canvas Stage 2: Converting the draggable element from div back to li when dropped i ...