0

I am trying to display days, hours, minutes, and seconds until next birthday. Birthday is calculated by prompt value. I have calculated seconds, minutes, hours and days. But I am getting wrong value e.g. "0". What's wrong in my code?

code:

<!DOCTYPE html>
<html>
<head>
    <style>

    p{
        text-align: center;
        font-family: monospace;
        font-size: 20px;
    }
    </style>
    <title>trail</title>

</head>
<body>
    <h1 style="text-align: center; font-family: monospace;"> My age </h1>
    <p id="dateField"> </p>
    <p id="birthField"> </p>
    <p id="nextBirth"> </p>

    <script>    

        var monthNames = ["January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November", "December"
        ];

        var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

        var today = new Date(); 

        var myMonth = prompt("What month were you born in?");
        var myDay = prompt("What day were you born on?");
        var myYear = prompt("What year were you born in?");

        var birthday = new Date(myYear, myMonth, myDay);  

        var dateLoc = document.getElementById("dateField").innerHTML = "Today is " + today;

        var birthField = document.getElementById("birthField")
        .innerHTML = "I was born on " + monthNames[myMonth - 1] + ' ' + myDay + ',' + myYear + '.' 
        + '(' + myMonth + '/' + myDay + '/' + myYear + ')';

        var years = today.getFullYear() - birthday.getFullYear();  

        var seconds = Math.floor( (years/1000) % 60 );
        var minutes = Math.floor( (years/1000/60) % 60 );
        var hours = Math.floor( (years/(1000*60*60)) % 24 );
        var days = Math.floor( years/(1000*60*60*24) );

        var nextBirth = document.getElementById("nextBirth").innerHTML = "I am " + years + "  Years old, and will turn " + (years + 1 ) + " in:" + "<br>" + days + " days," + hours + "hours," + minutes + "minutes," + seconds + "seconds";
    </script>
</body>
</html>
Riya
  • 415
  • 9
  • 23
  • 1
    What do you mean by *"**of** next birthday"*? Do you mean *"until"* the next birthday? – Phil Oct 15 '17 at 23:14
  • 1
    Math logic needs some rethinking also. Have to subtract days before calculating hours , subtract hours before calculating minutes etc – charlietfl Oct 15 '17 at 23:18
  • I suppose the main problem you have is `var years = today.getFullYear() - birthday.getFullYear()`. This will be something like `2017 - 1992` which is `25`. Think about that in regards to `(years/1000) % 60`, etc – Phil Oct 15 '17 at 23:19
  • @Phil I want to calculate days, hours, minutes, seconds left for next bierthday – Riya Oct 15 '17 at 23:19
  • @Phil that gives me birth year which I already calculated. – Riya Oct 15 '17 at 23:20
  • Yes, but `Math.floor( (25/1000) % 60 )` is `0`. Seems you think `years` is a millisecond value or something but it is not – Phil Oct 15 '17 at 23:21
  • 1
    Suggestion....hard code some values instead of prompts while you debug – charlietfl Oct 15 '17 at 23:22
  • @charlietfl that's not even the start of it. Calculating the answer accurately, taking into account all daylight savings changes, leap seconds, etc just makes my head hurt. I suppose OP could go for a very generalised solution with all the usual assumptions about timespans – Phil Oct 15 '17 at 23:22
  • 1
    @Phil this is a homework question, and typically those conditions are ignored on homework assignments. It's literally called `lab14` – Aanand Kainth Oct 15 '17 at 23:24
  • 1
    @AanandKainth surely going the extra mile could earn some extra credit :D – Phil Oct 15 '17 at 23:25
  • 1
    But maybe asking on Stack Overflow could give you "unextra" credit. ;) – Aanand Kainth Oct 15 '17 at 23:26
  • consider using moment.js – Doug Coburn Oct 15 '17 at 23:27
  • @Doug I want to calculate without using of moment.js – Riya Oct 15 '17 at 23:30
  • If anyone can help. – Riya Oct 15 '17 at 23:31
  • 1
    We aren't a homework answering service. @Phil already pointed out your issue. I'd try getting the difference in milliseconds and work up, rather than down from the difference in years. – Doug Coburn Oct 15 '17 at 23:39
  • 1. check if next bday is in this year or next year -> save year in var nextBdayYear 2. create a var nextBday = Date(nextBdayYear, myMonth, myDay) 3. create a var today = Date.now(); 4. create var diff = nextBday.getTime() - now 5. **use diff value for your calculations** and not your var years – Andrea Oct 15 '17 at 23:58
  • @Andrea birth date is not fixed. it depends upon user entered value in prompt. I already created the steps you mentioned. – Riya Oct 16 '17 at 00:16
  • @Riya in your code your are using 'years' for calcs, not 'diff' – Andrea Oct 16 '17 at 00:20
  • @Andres I just need to follow steps given by you ? – Riya Oct 16 '17 at 00:33
  • Probalby a duplicate of [*Difference between two dates in years, months, days in JavaScript*](https://stackoverflow.com/questions/17732897/difference-between-two-dates-in-years-months-days-in-javascript). – RobG Oct 16 '17 at 01:48

3 Answers3

0

(Not accounting for leap years/seconds, etc.)

Using new Date() the month passed starts at 0 for January. You could use:

var myMonth = prompt("What month were you born in?") - 1;

Now your variable birthday will store the correct month.

For birthField you can then change monthNames[my Month - 1] to monthNames[my Month]

For years you are only subtracting the birth year from the current year. If one's birthday hasn't occurred yet this year, years will be off. We will resolve this later.

We need to figure out the correct date for the user's next birthday. It is either this year or next year. It might be handy to store the date of their birthday this year in a variable:

var thisYearsBirthday = new Date(today.getFullYear(), myMonth, myDay);

We could then store a variable for the year of the user's upcoming birthday, assuming that it is next year:

var nextBirthdayYear = today.getFullYear() + 1;

Then we could check if thisYearsBirthday is in the future, and if so change nextBirthdayYear to be this year. We should also change years to reflect that the user's birthday hasn't happened yet this year.

if ( today < thisYearsBirthday ) {
  nextBirthdayYear = today.getFullYear();
  years = years - 1;
}

Now we can store the user's correct next birthday:

var nextBirthday = new Date( nextBirthdayYear, myMonth, myDay );

We can store how many milliseconds are left until the user's next birthday:

var milliseconds = nextBirthday - today;

Your variables seconds, minutes, hours and days are not formulas based on years, they are base on milliseconds. We should put the milliseconds variable in there:

var seconds = Math.floor( (milliseconds/1000) % 60 );
var minutes = Math.floor( (milliseconds/1000/60) % 60 );
var hours = Math.floor( (milliseconds/(1000*60*60)) % 24 );
var days = Math.floor( milliseconds/(1000*60*60*24) );

This should result in the correct days, hours, minutes, and seconds until next birthday being displayed.

uturnr
  • 2,516
  • 2
  • 12
  • 11
  • There was an issue in my code where if the user's birthday was in the next day or two, the age displayed might be a year too old. To resolve this, I changed the `years` declaration back to what you originally had, and then adjusted `years` in the if statement that checks if the user's birthday has happened yet this year. I have edited the answer above. – uturnr Oct 16 '17 at 01:26
-1

Hi You are missing that calculating next birthday that it should be below code

myMonth--;
var nextBirthday = (new Date(today.getFullYear(), myMonth, myDay))<today?(new Date(today.getFullYear()+1, myMonth, myDay)):(new Date(today.getFullYear(), myMonth, myDay))

And you can find working code below

var today = new Date();

var myMonth = prompt("What month were you born in?");
var myDay = prompt("What day were you born on?");
var myYear = prompt("What year were you born in?");

var birthday = new Date(myYear, myMonth, myDay);
console.log(birthday);

var dateLoc = document.getElementById("dateField").innerHTML = "Today is " + today;

var birthField = document.getElementById("birthField")
    .innerHTML = "I was born on " + monthNames[myMonth - 1] + ' ' + myDay + ',' + myYear + '.'
    + '(' + myMonth + '/' + myDay + '/' + myYear + ')';

var milliseconds,seconds,minutes,hours,days;

var years = today.getFullYear() - birthday.getFullYear();

//Here is my code 
 myMonth--;// Because of Month index is 0-11
var nextBirthday = (new Date(today.getFullYear(), myMonth, myDay))<today?(new Date(today.getFullYear()+1, myMonth, myDay)):(new Date(today.getFullYear(), myMonth, myDay)) //checking is passed or not
var diff = nextBirthday-today;

milliseconds=diff%1000;
diff=(diff-(milliseconds))/1000;
console.log(diff);
seconds=diff%60
console.log(diff);
diff=(diff-seconds)/60;
console.log(diff);
minutes=diff%60
diff=(diff-minutes)/60;
console.log(diff);
hours=diff%24
days=(diff-hours)/24;
console.log(diff);

var nextBirth = document.getElementById("nextBirth").innerHTML = "I am " + years + "  Years old, and will turn " + (years + 1 ) + " in:" + "<br>" + days + " days," + hours + "hours," + minutes + "minutes," + seconds + "seconds";
Ferhat BAŞ
  • 797
  • 7
  • 12
  • As below: you are assuming that next birthday is in next year. this is not always true – Andrea Oct 16 '17 at 00:20
  • Yeah it is true, sorry – Ferhat BAŞ Oct 16 '17 at 00:25
  • @FerhatBAŞ Thank you. What if I also want to count total days, hours, minutes and seconds I have been alive for ? – Riya Oct 16 '17 at 01:00
  • Just change diff variable like this var diff = today-birthday; but you should be careful about month index, I didn't change your birthday calculation "var birthday = new Date(myYear, myMonth, myDay);" this gives to you one more moth. – Ferhat BAŞ Oct 16 '17 at 01:04
-2

So you're trying get the days, hours, minutes, and seconds until my next birthday. The problem is you are basing your equation on too little information. Here's the problem.

var years = today.getFullYear() - birthday.getFullYear();
//with example values: 30 = 2017 - 1987

//Here you try to get values from 30
var seconds = Math.floor( (years/1000) % 60 );
var minutes = Math.floor( (years/1000/60) % 60 );
var hours = Math.floor( (years/(1000*60*60) ) % 24 );
var days = Math.floor( years/(1000*60*60*24) );

The trouble is that Date.prototype.getFullYear() only returns the year, so subtracting one 'fullYear' from another just gives you your age, but doesn't return any other information. To get the results you want you need to find some way to pass on a little more information. My suggestion would be to add something like the following.

var years = today.getFullYear() - birthday.getFullYear();

//Edit: it's been pointed out that not everyone's next birthday is next year. This solution still works, but we need to add conditional logic to this next statement.
if ( today.getMonth() > birthday.getMonth() || (today.getMonth() === birthday.getMonth() && today.getDay() >= birthday.getDay() )) {
   var nextYear = today.getFullYear()+1;
}

var nextBirthday = birthday;
nextBirthday.setFullYear(nextYear);

//This converts nextBithday into milliseconds since 1970. Use Date.getTime() to do the same to today and subtract.
var timeToNextBday = nextBirthday - today.getTime();

//From here use math to get the precise days and time until your next birthday
  • you are assuming that next birthday is in next year. this is not always true – Andrea Oct 16 '17 at 00:13
  • Hmm, I suppose you're right! Mine is so I didn't think it through any further. This is fixed with a conditional statement "if today's month > bday month, add a year". And similar for days. – trentstenoien Oct 16 '17 at 00:23