What is the process for increasing the number of days in a timestamp?

I am struggling to calculate the correct end date from a given start date and duration in my code.

exports.terminateStoreAd = functions.https.onRequest(async(req, res) => {
        try {
            const snapshot =await admin.database().ref("StoreAds").once("value");
            if (snapshot.exists()) {
                snapshot.forEach(snapData => {
                    if (snapData.exists()) {
                        const endDate=new Date(snapData.val().startDate).getTime()+(snapData.val().duration*24*60*60*1000);
                        res.send(""+endDate);
                    }
                });
                res.send("done")
            }
        } catch (error) {
            console.log("terminateStoreAd error :" + error.message); 
        }
    });

Given data:

Start date: 1559449773

Duration: 5 days

Incorrect end date calculation: 1991449773

I appreciate your assistance in fixing this issue. Thank you!

Answer №1

When working with date calculations in JavaScript, it's important to consider whether the startDate is already in milliseconds or a Date string. To convert the required date into milliseconds, you can use the following code:

If startDate is in milliseconds:

const endDate = snapData.val().startDate + snapData.val().duration*24*60*60*1000;

On the other hand, if startDate is a Date string:

const endDate = (new Date(snapData.val().startDate)).getTime() + snapData.val().duration*24*60*60*1000;

This code snippet will help you obtain the endDate in milliseconds for your calculations.

Answer №2

If we have a start date of 2019-05-01, determining the date that is 5 days later can be achieved by simply creating a new date with the appropriate parameters.

It's important to remember that the month in JavaScript is zero-indexed, meaning May (the 5th month) is actually index 4. So, if I want the date 5 days after May 1st, I would use 1+5 as the day value:

const startDate = new Date(2019, 4, 1);
const endDate = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate()+5);

console.log(`Start Date: ${startDate}, End Date: ${endDate}`);
console.log(`Start Date: ${startDate.valueOf()}, End Date: ${endDate.valueOf()}`);

Answer №3

finally found the solution I was looking for!

exports.endStoreAd = functions.https.onRequest(async(req, res) => {
try {
    const snapshot = await admin.database().ref("StoreAds").once("value");
    const promises = [];
    if (snapshot.exists()) {
        snapshot.forEach(childSnapshot => {
            const endTime = childSnapshot.val().startTime + childSnapshot.val().duration  * 86400;
            const todayTime = Math.round(new Date().getTime()/1000);
            if (endTime <= todayTime) {
                promises.push(
                    admin.database().ref("StoreAdsHistory").child(childSnapshot.key).set(childSnapshot.val()),
                    childSnapshot.ref.remove(),
                    res.send()
                );
            }
        });
       } 
       await Promise.all(promises);
    } catch (error) {

}

});

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

Deleting an item from an array in MongoDB

I am facing a challenge with removing a specific object from my mongoDB array. The item inside the red cube needs to be removed, but I'm not sure how to do it (0: Object) https://i.sstatic.net/VL8TF.png I attempted the following method but it did n ...

When working with Typescript, encountering difficulty in locating or importing modules from a parent directory that is one level above the tsconfig.json file is

My project's directory structure looks like this: Main/project-root/* (tsconfig.json, packages.json, app.ts, etc are located here) Main/shared/* (shared.ts is located here along with other ts files, no packages.json or any other files) Let's ...

Tips for resolving TS7022 issue within Vue Composition API

I encountered an issue while attempting to import a component in my file that generated the following error message: TS7022: 'default' implicitly has type 'any' because it does not have a type annotation and is referenced directly or in ...

Compiling and rendering HTML code from a file with AngularJS

Here is the custom directive code that I have created: angular.module('app.directives', []).directive('userHeader', ['authService', '$compile', function(authService, $compile) { return { restrict: 'AEC&ap ...

Creating a seamless integration between Angular 2's auth guard and observables to enhance application security

I'm having trouble setting up an auth guard for one of my routes because I am unsure how to implement it with an observable. I am using ngrx/store to store my token. In the guard, I retrieve it using this.store.select('auth'), which returns ...

What is the best way to incorporate a Json file into a JavaScript file?

Using JSON data in JavaScript I recently wrote a JavaScript program that selects a random "advice number" between 1 and 50. Now, I need to figure out how to access a JSON file for the advice messages. JavaScript file: Advice_number = Math.floor(Math.ran ...

Exploring the creation of an Angular service that utilizes HttpClient for making GET requests, with a focus on the different

I've been diving into Angular lately and I'm facing some challenges with handling get requests. If you're interested, you can check out my code on Angular Stackblitz import { HttpClient} from '@angular/common/http'; import { Inject ...

Retrieving the maximum values from JSON data using D3

Currently, I am working with D3 and JSON data by using a function that looks like this: d3.json("http://api.json", function(jsondata) { var data = jsondata.map(function(d) { return d.number; }); After executing this, the value of the data becomes ["2", ...

What is the best way to convert the javascript code into clojurescript?

Looking to utilize capacitor/app in order to determine the state (background or active) of my iOS app. My project is built on Clojurescript, so I need to convert the following javascript code into a clojurescript equivalent. Javascript import { App } fro ...

I am looking to implement pagination in my Elasticsearch outcomes by incorporating a new set of results beneath the existing one using React JS

My current project involves developing a user interface using ReactJs for a search engine that utilizes elasticsearch to return 20 results per page. The issue I am facing is that when the next button is clicked, it replaces the old results with the new one ...

Angular's Not In operator can be used to filter out unwanted

As a newcomer to Angular, I am attempting to implement a basic if statement to verify that my property does not match one of 10 specific values. Is there a method or filter within enums or lists that can achieve this easily? public type: string; if(type = ...

Pressing buttons activates key responses

My goal is to create buttons labeled "Correct" and "Incorrect" that trigger key presses of 'c' and 'i'. I am currently working with a jspsych plugin that only accepts key press responses. Although the buttons are displaying properly, I ...

Upload the image data into the input file tag

Is there a way to take a string code stored in a JavaScript variable that is retrieved from the Cropit plugin (used for cropping images) and then set this information into an input file tag? I want to be able to send it via AJAX to PHP. Here is the JavaSc ...

Preserving client-side page state during page reloads in angular.js apps

I am currently developing a Single Page application using angular.js and I have encountered an issue that I am struggling to resolve. When performing a full page refresh in an angular app, how can we verify if the user still has a valid session? While Sta ...

Is the size of the array significant in the context of JavaScript here?

Whenever a button is clicked on the page, I am dynamically creating an array in javascript using item id's fetched from the database. Each entry in the array will hold a custom object. The id's retrieved from the database can range from numbers ...

Tips for recognizing users in socket.io?

I'm currently developing a chat application with socket.io. However, one issue I am facing is identifying the sender of a message. Unlike in Express where we have the "req" (request) variable to easily identify users, socket.io does not provide such f ...

Displaying JavaScript Countdown in PHP Table

I have a database table with multiple fields and I am looking to create a countdown using the integer value from one of the fields (in minutes). How can I loop through and display the countdown for each row in a PHP table utilizing these values, with the a ...

Generating an array of keys from duplicated values in Typescript

My data is structured in the following array format: { itemTitle: 'value example', itemType: 'value example', itemDescription: 'value example', itemFamily: 'Asset', }, { itemTitle: 'val ...

The initial size of C3 charts is unnecessarily large upon loading

I am utilizing the C3 JavaScript library to showcase graph data on my webpage. Initially, when the page loads, the graphs remain hidden until a specific "tab" is selected. However, I am encountering an issue where the first graph does not fit within its de ...

Understanding surface orientations of moving objects

I am experimenting with creating a software-based vertex animation for a mesh. It's like a vertex shader, but done in software rather than hardware. Essentially, I am applying a transformation matrix to each vertex of the mesh. While the mesh itself ...