Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Calculation with dates doesn't work

Coffee

New Coder
Dear experts

I'm not really used to javascript, and I maybe have a silly problem.
In my script I want to calculate the date of today minus a earlier day and need the numbers of day.
Javascript is calculating in milliseconds, right? I get a number of days but they are really wrong.
Do I have to bring the "today"-day in a specified formatting?


JavaScript:
<html>
<head>

</head>
<body>
        <h1> Statistik Nummernverbrauch </h1>
        <p> Datum im Format [dd.mm.yyyy] eingeben: </p>
        <input type="text" name="letztesDatum" id="LastDate" value="">
        <button onclick="Berechnung()">Start</button>
        <br/>
        <br/>
<script>
function Berechnung() {
var d0 = document.getElementById("LastDate").value;
var d1 = new Date(d0);
var d2 = new Date();
var diff = d2.getTime() - d1.getTime();

var daydiff = (diff / 86400000).toFixed(0);


document.write(" letzte Eingabe war vor <b> " + daydiff + " Tagen </b>" );
}
</script>
</body>

</html>
 
No, it's not the current date that is the problem. It is the Date object created from your input that is the problem. You enter the date as
dd.mm.yyyy but when you for example enter 01.09.2022, the resulting Date is Sun Jan 09 2022 00:00:00 GMT+0100 (Central European Standard Time). Evidently, the data must be entered as mm.dd.yyyy. When you do that, your code works correctly
I found this out by adding this line console.log("d1 = " + d1); but stepping through the code in the Debugger and looking at the Local variables would have been just as easy. If you're not familiar with your browser's debugger, do invest some time in it. It will really pay off.
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom