Is it possible to pass a variable as an input parameter in the Date constructor when creating a timestamp in Firebase

I'm looking to work with timestamp queries.

Note: setSD and setED are part of the Vue object's data, and the firebase function call is within the method.

callFirebase: function (){
        let startdate = new Date(this.setSD+'T00:00:00');
        let enddate = new Date(this.setED+'T00:00:00');
        console.log(startdate);
        console.log(enddate);
        db.collection("study").
        where("time", ">=", firebase.firestore.Timestamp.fromDate(startdate)).
        where("time", "<=", firebase.firestore.Timestamp.fromDate(enddate))
        .get().then(function (querySnapshot) {
            querySnapshot.forEach(function (doc) {
                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data().time.toDate());
            });
        })
            .catch(function (error) {
                console.log("Error getting documents: ", error);
            });
        }
    }

Error illustration:

https://i.sstatic.net/FX1Oo.png

callFirebase: function (){
        let startdate = new Date(this.setSD+'T00:00:00');
        let enddate = new Date(this.setED+'T00:00:00');
        console.log(startdate);
        console.log(enddate);
        db.collection("study").
        where("time", ">=", new Date(this.setSD+'T00:00:00')).
        where("time", "<=", new Date(this.setED+'T00:00:00'))
        .get().then(function (querySnapshot) {
            querySnapshot.forEach(function (doc) {
                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data().time.toDate());
            });
        })
            .catch(function (error) {
                console.log("Error getting documents: ", error);
            });
        }
    }

However, my attempts have led to the same issue.

callFirebase: function (){
        let startdate = new Date(this.setSD+'T00:00:00');
        let enddate = new Date(this.setED+'T00:00:00');
        console.log(startdate);
        console.log(enddate);
        db.collection("study").
        where("time", ">=", new Date('2019-12-31T00:00:00')).
        where("time", "<=", new Date('2020-01-01T00:00:00'))
        .get().then(function (querySnapshot) {
            querySnapshot.forEach(function (doc) {
                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data().time.toDate());
            });
        })
            .catch(function (error) {
                console.log("Error getting documents: ", error);
            });
        }
    }

My main confusion lies in why this particular setup works. I initially assumed that I couldn't use variables in the where clause. However, after further investigation, it seems that might not be the case. Can someone provide some assistance?

Answer №1

Here's how I tackled the issue on my own:

  updateDatabase: function (){     
        let startDate = new Date(this.setSD+'T00:00:00');
        startDate.setHours(startDate.getHours()+9);
        let endDate = new Date(this.setED+'T00:00:00');
        endDate.setHours(endDate.getHours()+9);
        console.log(startDate.toISOString());
        console.log(endDate.toISOString().split('.',1)[0]);
        db.collection("study").
        where("time", ">=", new Date(startDate.toISOString().split('.',1)[0])).
        where("time", "<=", new Date(endDate.toISOString().split('.',1)[0])).
        get().then(function (querySnapshot) {
            querySnapshot.forEach(function (doc) {
                // doc.data() is always defined for query documents
                console.log(doc.id, " => ", doc.data().time.toDate());
            });
        })
            .catch(function (error) {
                console.log("Encountered an error while retrieving documents: ", error);
            });
        }
    }

When initializing a new Date(), the default value of date.toISOString() is used in the where clause.

(for example, 2020-01-21T00:00:00.000Z)

Hence, I employ split () to format it as a string that conforms with the date constructor.

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

What is the method for incorporating a 3rd party npm module without utilizing npm install?

I'm in a situation where I need to utilize an outdated 3rd party npm module that cannot be directly used with npm i and reqiure. In order to customize it for my specific needs, I have to make some modifications to the source code of this npm module. ...

Transform your traditional sidebar into a sleek icon sidebar with Semantic UI

I am working on customizing the semantic-ui sidebar. My goal is to have it minimize to a labeled icon when the toggle button is clicked. However, I am having trouble with the animation and getting the content to be pulled when I minimize it to the labeled ...

Learning how to update a database using AJAX, jQuery, PHP, and MySQL can greatly enhance your web development

I am facing an issue with updating a database using AJAX without reloading the page. Even though I receive a success message after making the AJAX call, the database is not getting updated as expected. Here is my code: JS: $('.start-time-class' ...

At the moment of execution, the imported npm package module is not defined

Recently, I added a package named "js-linq" (available at https://github.com/battousai999/js-linq) using the command npm install js-linq and it seemed to install successfully. This process is clearly outlined in the npm documentation at https://www.npmjs.c ...

Instant urban locator

Is there a way to automatically populate the visitor's city in the membership form? Member Register Form Name: Emre Email:--- Pass:--- City: Istanbul // Automatically detected location How can I implement automatic location detection for the ...

Tips for merging ajax div elements

Here's a combination of my Ajax scripts, integrating the first and second versions: 1st <script> function Ajax() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp ...

Switching between languages dynamically with Angular JS using $translateProvider and JSON files

I currently have a collection consisting of 6 different JSON files. en.json es.json fr.json it.json ja.json zh.json An illustration of the data present in each file is as follows (in this instance, considering en.json): { "SomeText": "Test in Englis ...

How can you restrict a textbox input to accept only numerical values and decimals using ng-pattern?

I'm working on a code that needs to accept both decimals and integers. How can I verify this using the ng-pattern? An example of the code: Some test cases include: 1) 22 = Should pass, 2) 22.5 = Should pass, 3) 2a = Should fail, 4) @#@ = Should ...

JavaScript xPath is ineffective at providing a return value

Trying to work through an issue with xPath and I am new to this concept. Any guidance or assistance in JavaScript would be greatly appreciated. Here is the simple HTML document that I have: <!DOCTYPE html> <html> <head> < ...

Include a new item into the existing one and iterate through the information within it

Is there a way to iterate through the compositions array within the sample object and then use that data to fill the compositions array of the objToAdd object? const sample = { lin: { "clo": [ { "mode": 19, "id": ...

Angular HTML is throwing an error related to object arrays

Is there a way to display only specific fields of an array? <div class="form-check" *ngFor="let periodo of filterPeriodos()"> <div>{{periodo.periodos | json}}</div> <input class="form-check-input mr- ...

Why are cloned jQuery elements triggering events on the parent <div> and not the child <div>?

Currently, I am working on a tool that includes dynamic input fields for user input. To create different sections, I have cloned some divs from the code successfully. However, I am facing an issue where the events attached to the parent div are triggered e ...

Implementing a night mode switch in a Vuetify application version 2.0 built on Nuxt.js

I have integrated the nuxt.js vuetify template, and within the nuxt.config.js file, there is an object (shown below) that sets up the dark mode for the application. vuetify: { customVariables: ['~/assets/variables.scss'], theme: { ...

Creating a 404 Error Response in Express.js

Inside app.js, I currently have the following code: // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); This code executes when a non-existent URL ...

Can someone please help me understand why my CSS transform scale isn't functioning properly?

I've developed a JavaScript function that enlarges a button and then smoothly shrinks it back to its original size. The function successfully changes the color of the button to blue, but for some reason, it's not working with the transform prope ...

The issue of AngularJS failing to bind object properties to the template or HTML element

Just dipping my toes into angularJS, following Todd Motto's tutorials, and I'm having trouble displaying object properties on the page. function AddCurrentJobs($scope){ $scope.jobinfo = [{ title: 'Building Shed', description: ...

How can I send my response as JSON in the controller in Asp.net?

Whenever I use toastr for form notifications, I always seem to receive an error message even though the data is successfully saved in the database. I suspect that the error may be stemming from the controller because I am not sending back in JSON format. A ...

Edit the settings for the dual-axis line chart's parameters

After countless hours of scouring the Internet and numerous attempts, I have come to the decision to seek help by posting my issue on this forum. I must confess, I am not the best developer. My approach usually involves finding pre-existing code that I ca ...

The Axios GET request was not functioning properly after attempting to use Axios stream.on("data")

I am working with a backend API that has an endpoint named /subscribe, which gives back a continuous stream of data. Along with this, I have a node process, and I am utilizing axios to send a request to my backend API with a response type of "stream& ...

Unable to publish in an Express + Passport application / Test for user authentication

Currently, I am exploring the integration of Passport as an authentication middleware with Express and Angular in my development project. As a beginner to these frameworks, I have been conducting a test login implementation within the app. The key code sni ...