TIP about getting date ranges

Hey
Just wanted to share some functions I made for getting first and last days of a month and also monday and sunday of a week. Just send any date to the functions and they will return dates for you.

function getFirstDay(d){ // Returns date of first day in month
	var dt = new Date(d);
	return new Date(dt.getFullYear(), dt.getMonth(), 1);
}
function getLastDay(d){ // Returns date of last day in month
	var dt = new Date(d);
	return new Date(dt.getFullYear(), dt.getMonth() + 1, 0);
}
function getMonday(d) { // Returns date of monday in the week of date you send to the function
  d = new Date(d);
  var day = d.getDay(),
      diff = d.getDate() - day + (day === 0 ? -7 : 0);
  return new Date(d.setDate(diff));
}

function getSunday(d) { // Returns date of sunday in the week of date you send to the function
  d = new Date(d);
  var day = d.getDay()-7,
      diff = d.getDate() - day;
  return new Date(d.setDate(diff));
}

They are nice to have when you have to calculate range in dates before making a data collection query.

5 Likes

Thank you Andreas, this is really helpfull.

But, what about date increment? how can I add 30 Days to the current date? I have problems with February and with months with 31 days. I ended up doing an extremely large function not too clean to the eyes. I’m sure there must be a straightforward solution.

Any help will be very much appreciated
Thank you!

I will look into that later

I knew there would be an easy way to do arithmetic operations with dates, actually pretty simple:

var TodaysDate = new Date();
TodaysDate.setMonth(TodaysDate.getMonth()+1);

There is a complete set of Methods for date objects specifically designed to perform arithmetic operations with dates.

Thanks for the reply

2 Likes

Is there a way to calculate a value based on a fixed start date and the current date?

Hi Jerry,

What value do you want? If it’s the difference between two dates, then it would be something like this:

var date1 = new Date("1/5/2018");
var date2 = new Date();  // today
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // get time diff in milliseconds
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));  // convert milliseconds to days

For different date calculations, you can do an Internet search and find gobs of useful stuff.

I hope this helps,

Yisrael

2 Likes

I am having a problem with your code Yisrael. Its hows there is an error with last bracket. Here is smy code;

import wixData from ‘wix-data’;

$w.onReady( function () {
$w(“#dataset3”).onReady( () => {
var date1 = itemData._createdtedDate;
var date2 = new Date(); // today
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // get time diff in milliseconds
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$w(“#dataset3”).onReady( () => {
{ if (timeDays > 0) {

        $w("#text16").text = "40" 

    } 

else
{
let daysLeft =40* timeDays;
$w(“#text16”).text = daysLeft.toString();
}
}

I want to get the total records less than 12 hours as well as more than 12 hours and less than 24 hours and records more than 24 hours.
Note . I have a data containing requests and recorded by dates
Can you help me by asking an example

make the total im textbox

This should get your started:

JavaScript getTime() Method

Use something like this to establish your boundaries:

var time = new Date().getTime();	// date in milliseconds
    var timeMinusTwelveHours = time - (12 * 60 * 60 * 1000);	
                 // hours * minutes * seconds * milliseconds
    var timeMinusTwentyFourHours = time - (24 * 60 *60 * 1000); 
    var dateNow = new Date();
    var dateMinusTwelveHours = new Date(timeMinusTwelveHours);
    var dateMinusTwentyFourHours = new Date(timeMinusTwentyFourHours);

Then do a query on your records with these boundaries:
Query between values

Something like:

import wixData from 'wix-data';

// ...

wixData.query("myCollection")
  .between("date", dateNow, dateMinusTwelveHours)
  .find()
  .then( (results) => {
    if(results.items.length > 0) {
      let items = results.items;
      let firstItem = items[0];
      let totalCount = results.totalCount;
      let pageSize = results.pageSize;
      let currentPage = results.currentPage;
      let totalPages = results.totalPages;
      let hasNext = results.hasNext();
      let hasPrev = results.hasPrev();
      let length = results.length;
      let query = results.query;
    } else {
      // handle case where no matching items found
    }
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );
2 Likes

wooow … this is another code I look
nice code I will use in another process
thank brainstorrrm

But my question is how late orders are calculated
Example: I have orders that are either closed or still open
I would like to know the count number of orders that are still open and not closed
The method you mentioned is a query by today’s date
While I want to query based on the date of the orders ( use order date in my data )
count : Order date + 12 hours?
count : Order date more than 12 hours and less than 24 hours
count : Order date more than 24 hours
my data collection name : data937
date field : orderdate
status field : status

and add the results in $w(‘#textcount12)
$w(’#textcount24)

" The method you mentioned is a query by today’s date (only)"
You need to read up on how Unix/JS does date and time.
Any date variable by definition has time included (whether you specify it or not) and at the core represents milliseconds since 01/01/1970. You can then take this moment in time and display it in whatever form you need.

Once you understand that, you’ll understand what this simple code does.
You set the boundaries as needed (moments in time), then make your queries accordingly.

I’m assuming you are looking back 12 hours and 24 hours and you want just a count of orders in these time frames (last 12 hours, between 12 and 24, more than 24 hours) based on their status (open, closed).

Use the code above to establish the 12 and 24 hour boundaries.

Then use between queries with a simple count:

import wixData from 'wix-data';

// ...
// for all orders that have been placed in the last 12 hours:

 wixData.query("data937")
  .between("orderdate", dateNow, dateMinusTwelveHours)
  .count()
  .then( (num) => {
    let numberOfItems = num;
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );
  
  $w("#textcount").text = num;  // display query total count

A query for all orders that have been placed in the last 12 hours and are still “open”

import wixData from 'wix-data';

// ...
// for all orders that have been placed in the last 12 hours and are still "open"

 wixData.query("data937")
  .between("orderdate", dateNow, dateMinusTwelveHours)
  .eq("status", "open")   // or whatever status you need
  .count()
  .then( (num) => {
    let numberOfItems = num;
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );
  
  $w("#textcount").text = num;  // display query total count

A query for all orders that have been placed between the last 12 hours to 24 hours and are “closed”

import wixData from 'wix-data';

// ...
// for all orders that have been placed between the last 12 hours to 24 hours and are "closed"

 wixData.query("data937")
  .between("orderdate", dateMinusTwelveHours, dateMinusTwentyFourHours)
  .eq("status", "closed")   // or whatever status you need
  .count()
  .then( (num) => {
    let numberOfItems = num;
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );
  
  $w("#textcount").text = num;  // display query total count

I can’t write your code for you, but these examples should help you get started on your quest.

1 Like

Thanks for the help me

But the result is 0
Can you explain why

Take a look at wix-dataset

$w("#myDataset").onReady( () => {
  console.log("The dataset is ready");
} );

Place all your code inside the dataset “.onReady()” statement.
You want your code to execute once the database connection is loaded and operating - otherwise you get “0” or random results.

Also, add a few console.log statements to verify that the date/time variables are the way you intend them to be - if you don’t know what that is, google “browser console.”
To open the developer console window on Chrome, use the keyboard shortcut Ctrl Shift J (on Windows) or Ctrl Option J (on Mac). Alternatively, you can use the Chrome menu in the browser window, select the option “More Tools,” and then select “Developer Tools.”

import wixData from 'wix-data';
// ...

$w.onready(function() {     // regular page onReady()

    var time = new Date().getTime();	// date in milliseconds
    var timeMinusTwelveHours = time - (12 * 60 * 60 * 1000);	
                 // hours * minutes * seconds * milliseconds
    var timeMinusTwentyFourHours = time - (24 * 60 *60 * 1000); 
    var dateNow = new Date();
    var dateMinusTwelveHours = new Date(timeMinusTwelveHours);
    var dateMinusTwentyFourHours = new Date(timeMinusTwentyFourHours);

// verify boundaries 
console.log("dateNow: " + dateNow);
console.log("dateMinusTwelveHours: " + dateMinusTwelveHours);
console.log("dateMinusTwentyFourHours: " + dateMinusTwentyFourHours);


$w("#937").onReady( () => {    // your dataset onReady()
// for all orders that have been placed in the last 12 hours:

 wixData.query("937")
  .between("orderdate", dateNow, dateMinusTwelveHours)
  .count()
  .then( (num) => {
    let numberOfItems = num;
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );
  
  $w("#textcount").text = num;  // display query total count
  
} ); // end of dataset.onReady()
} ); // end of regular page onReady()

1 Like

I’m really sorry … brainstorrrm
The code is working properly
But it seems that the problem I have is the date format
Is there a solution to this problem?

Not sure where you’re hanging.
If you placed the query inside the dataset.onReady you should be getting results with this code and the dates you’re showing in the collection.

Another thing to consider to do this correctly - you need to ensure that the query time is compatible with the collection time as far as timezone is concerned. To prevent timezone problems, I do all my date/time collections, queries and calculations in UTC time, with:
JavaScript setUTCDate() Method
JavaScript setUTCFullYear() Method
JavaScript setUTCHours() Method

Looking at your console.log and collection orderdate, it seems that this should not be a problem for you.

Wow I found the problem
The old history must be put first and then the new history
Between (Old History) and (New History)
The code is working properly
Really thank brainstorrrm


import wixData from 'wix-data';
// ...

$w.onready(function() {     // regular page onReady()

    var time = new Date().getTime();	// date in milliseconds
    var timeMinusTwelveHours = time - (12 * 60 * 60 * 1000);	
                 // hours * minutes * seconds * milliseconds
    var timeMinusTwentyFourHours = time - (24 * 60 *60 * 1000); 
    var dateNow = new Date();
    var dateMinusTwelveHours = new Date(timeMinusTwelveHours);
    var dateMinusTwentyFourHours = new Date(timeMinusTwentyFourHours);

// verify boundaries 
console.log("dateNow: " + dateNow);
console.log("dateMinusTwelveHours: " + dateMinusTwelveHours);
console.log("dateMinusTwentyFourHours: " + dateMinusTwentyFourHours);


$w("#937").onReady( () => {    // your dataset onReady()
// for all orders that have been placed in the last 12 hours:

 wixData.query("937")
  .between("orderdate", dateMinusTwelveHours , dateNow)
  .count()
  .then( (num) => {
    let numberOfItems = num;
    $w("#textcount").text = numberOfItems ; 
  } )
  .catch( (error) => {
    let errorMsg = error.message;
    let code = error.code;
  } );
  
   
 

Oh, but of course.
Glad you figured it out.