How can I use Javascript to calculate the daily price increase over a specific timeframe?

I have searched extensively, but I couldn't find anyone discussing this particular topic.

Between April 1st and August 1st, a price starting at $900 gradually increases to $1500. This amounts to approximately $5 per day, with the following formula:

ROUND(1500 - (600 * ((DEADLINE - TODAY) / (DEADLINE - START)))

My challenge is converting this formula into JavaScript and HTML so that I can display it in a sentence like "Today you'll have to pay $920."

This is my progress so far, but I am struggling to reset today's date for accurate calculations:

<div id="foo"></div>


  <script type="text/javascript">

      function getDayDiff(a, b) {
        return (a - b) / 8.64e7;
    }

    function getPayAmount(DEADLINE, TODAY, START) {
        return Math.round(1500 - (600 * getDayDiff(DEADLINE, TODAY) / getDayDiff(DEADLINE, START)));
    }
    
 document.getElementById("foo").innerHTML = "Today you'll have to pay $"  + getPayAmount(new Date(2021, 08, 1), new Date(), new Date(2021, 4, 1));
    </script>  

Answer №1

Begin by determining the number of days since Unix time, utilizing the getTime() method to obtain milliseconds, then apply the same calculation.

const days = (date) => Math.ceil(date.getTime() / (24 * 60 * 60 * 1000));

const DEADLINE = days(new Date("2021-08-01"));
const START = days(new Date("2021-04-01"));
const TODAY = days(new Date());

const res = Math.round(1500 - 600 * ((DEADLINE - TODAY) / (DEADLINE - START)));

console.log(res);

document.querySelector('.adbox.adred').append(`Today's Rate ${res}`)

Answer №2

Here’s a way to achieve this using JavaScript:

    function calculateDayDifference(start, end) {
        return (end - start) / 8.64e7;
    }

    function calculatePaymentAmount(deadline, today, start) {
        return Math.round(1500 - (600 * calculateDayDifference(deadline, today) / calculateDayDifference(deadline, start)));
    }
    
    document.getElementById("output").innerHTML = "You need to pay $" + calculatePaymentAmount(new Date(2021, 12, 31), new Date(2021, 4, 3), new Date(2021, 1, 1));
<div id="output"></div>

Explanation:

  • 8.64e7 represents the number of milliseconds in a day
  • Date differences are calculated in milliseconds
  • The payment amount is rounded using Math.round

Additional Note

An alternative method shared is as follows:

<div id="output"></div>


  <script type="text/javascript">

      function calculateDayDifference(start, end) {
        return (end - start) / 8.64e7;
    }

    function calculatePaymentAmount(deadline, today, start) {
        return Math.round(1500 - (600 * calculateDayDifference(deadline, today) / calculateDayDifference(deadline, start)));
    }
    
 document.getElementById("output").innerHTML = "Today's payment: $"  + calculatePaymentAmount(new Date(2021, 08, 1), new Date(2021, 4, 6), new Date(2021, 4, 1));
    </script>  

To reset the time portion and focus on the date only, you can use:

 var currentDate = new Date();
 currentDate.setHours(0, 0, 0);
 document.getElementById("output").innerHTML = "Amount due today: $"  + calculatePaymentAmount(new Date(2021, 08, 1, 0, 0, 0), currentDate, new Date(2021, 4, 1, 0, 0, 0));

Answer №3

While there is room for optimization, I wanted to demonstrate how you can utilize all the variables effectively.

// Define two dates and assign them to variables
let dateStart = new Date("04/01/2020");
let dateEnd = new Date("08/01/2020");

// Calculate time difference between the two dates
let timeDifference = dateEnd.getTime() - dateStart.getTime();

// Calculate number of days between the dates
let daysDifference = timeDifference / (1000 * 3600 * 24);

// Set initial and final price values
let initialPrice = 900;
let finalPrice = 1500;

// Calculate price difference
let priceDifference = finalPrice - initialPrice;

// Determine price change over time period in two decimal places
let PriceChangeOverPeriod = (priceDifference / daysDifference).toFixed(2);

document.write(PriceChangeOverPeriod);

Experience the code live at: https://jsfiddle.net/ugzn2y7s/

Answer №4

I calculated the payment rate using the starting, end, and current date,

Then I determined the amount that should have been paid today by adding the rate to the starting amount

const today = new Date();
const startDate = new Date('April 1, 2021');
const endDate = new Date('August 1, 2021');
const deadline = (endDate - startDate) / (1000 * 60 * 60 * 24);
const daysDiff = (today - startDate) / (1000 * 60 * 60 * 24);

const rate = Math.round((1500 - 900) / deadline);

document.body.innerText = `The expected payment for today should be $${Math.round((daysDiff * rate) + 900)}`;

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

Filtering out any inappropriate characters from the XML data before processing it with the XMLSerializer function

I am currently working on a solution to store user-input in an XML document using client-side JavaScript and then transmit it to the server for persistence. One specific issue that I encountered was when a user input text containing an STX character (0x2) ...

Tips for inserting a variable into an attribute value when creating it using TypeScript

this.listvalue; list.forEach((v: any) => { v.data.forEach((v2: any) => { this.searchlist.push({ header: v.header, value: v2.value_0 }); }); }); Is there a way to replace v2.value_0 with v2.this.listvalue? I've tried ...

Using Javascript to iterate through an array of images can display a placeholder image as the previous or next image when the loop reaches the beginning or end of the array

https://i.sstatic.net/Hd1N1.png //array of images const programmingLanguages = [jsIcon, htmlIcon, cssIcon, csharpIcon]; Functions for displaying next and previous images. function incrementLanguage() { if (languageIndex + 1 === programmingLangu ...

I am facing a NullPointerException error within my Java code

I'm facing an issue with my code and can't figure out why it's throwing this error. I have a generic array that has a maximum capacity of 100, and when the current size reaches this number, the max capacity is doubled. However, whenever I ru ...

Tips for correctly deciphering a JSON string that has been encoded using Html.Raw(Json.Encode(Model)):

Encoding model data into an HTML element can be done like this: @Html.Raw(Json.Encode(Model)); The resulting JSON string appears as follows: {"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo ...

Running unit tests on the interceptor using axios results in an error

I'm currently working on writing Unit tests for my Nestapp. Specifically, I am focusing on the interceptor file and trying to create a test case that will throw an error when the condition error.message.indexOf('timeout') >= 0 is met, and ...

Creating a customized greeting message using discord.js

I've been working on creating a Discord bot using discord.js, and I'm trying to figure out how to make the bot send a welcome message when a new member joins the server and opens a chat with the bot. The message should be something like "Hi there ...

Is it possible to delete XHR cache data from the client side?

Is it possible to clear cached XHR data on the client using JavaScript or its libraries? I am looking to test my app on multiple local hosts and would like to clear XML HTTP Requests on the client side instead of on the server. Is there a way to do this? ...

Issue with the express server's POST method and fetch causing undefined values to appear during a login process

Currently, I am in the process of learning how to create a basic login functionality for a Chrome extension that I am working on. My approach involves collecting a username and password from two input boxes and then sending this information to a server usi ...

Is there a term similar to "Rise above the Rest" in the world of Web Development?

Hey, I've encountered a new issue right now. Currently, I have two elements that are fixed to the top and bottom of the page. However, the elements in between them are overlapping the top element. Even though I tried keeping both elements fixed, th ...

The function "element.join" is not a valid function

Currently, I am working on a project where I need to write a list of IDs into an external file using Node.js. Despite successfully creating the file with the nodejs file system and attempting to write into it, my program crashes and displays the error mess ...

Sending information from one page to another and then sending it once more

I am currently utilizing the following code to submit a form's data to : <script type="text/javascript"> $(document).ready(function(){ $("#textnextofkin").validate({ debug: false, rules: { ...

How can I prevent the state from being overridden in the reducer function when updating the State Context API?

I'm currently facing an issue with my reducer case where it ends up overwriting the passed id instead of simply adding to the existing array of ids. Can you enlighten me on the fundamental concept behind state copying and clarify when to utilize the s ...

Why am I encountering a type error in NodeJS when utilizing the ping module?

I'm currently working on creating a simple app for pinging an IP address. The HTML form I've created has one input field for the IP address, which is then sent to NodeJS for processing. I am utilizing the ping module to retrieve the results. Ever ...

What is the best way to update my real-time search results by clicking on the clear button inside the search input field using JavaScript?

I’ve been working on implementing a live search feature. I managed to create live search using ajax, so it displays results that match the alphabet or word I type in. However, I encountered an issue with the cross button inside the search field. When cli ...

Merging two arrays of objects from the same response in JavaScript

How can I efficiently merge two arrays of objects from the same response? let data = [{ "testLevel":"mid", "testId":"m-001", "majorCourse": [ { "courseName":"C++" ...

Insert variable names within a function in R

I am looking to reformat a dataframe in the following manner: year1 <- rep(2001, 5) b <- c("","","120","","131") d <- c(letters[1:5]) year2 <- c("","","2002"," ...

Error: The React component throws a TypeError because it is unable to read the property 'map' from an undefined source

I encountered the following error TypeError: Cannot read property 'map' of undefined at ListItemFactory.ts:84:57 at The specific line where the error occurs is: return announcementitems=json.value.map((v,i)=>( To provide mor ...

Achieve a fading effect on an element as you scroll down the page

I successfully implemented a toggle audio button on my website, but now I would like it to fade in along with the scroll-to-top button that I also have (which operates similarly to the buttons on scrolltotop.com). Is there a simple way to achieve this? He ...

Is it better to define functions in the .h file, or should I simply declare them?

As a beginner in C programming, I recently stumbled upon this guideline: "Functions should be declared in .h files and only defined as inline functions." This raised a question for me - if functions are not to be defined in header files, then where exa ...