0

Today I'm training with the date in Javascript.

I displayed today's date and the milliseconds since 01/01/1970.

Now I would like to display the milliseconds since my birth, but don't know why one of my functions produces wrong results.

First one works correctly, but in the second function the milliseconds count stays fixed.

This example works:

function elapsedTime(id) {
  date = new Date()
  epoque = date.getTime()

  if (epoque < 10) {
    epoque = "0" + epoque
  }

  resultat = epoque + ' millisecondes ce sont écoulées depuis le 1er janvier 1970'
  document.getElementById(id).innerHTML = resultat
  setTimeout('elapsedTime("' + id + '");','1000')

  return true;
}

This example doesn't work:

function myBirthday(id) {
  birthday = new Date('september 15, 1986 14:29:00')
  milliseconde = birthday.getTime()

  if (milliseconde < 10) {
    milliseconde = "0" + milliseconde
  }

  resultat = milliseconde + ' millisecondes ce sont écoulées depuis ma naissance'
  document.getElementById(id).innerHTML = resultat
  setTimeout('myBirthday("' + id + '");','1000')

  return true;
}

I don't understand where is my mistake.

Thanks for help.

Ogochi
  • 320
  • 3
  • 12
  • 1
    What "doesn't work" about the second piece of code? – Scott Hunter Aug 28 '19 at 19:35
  • setTimeout uses an integer and you are passing in a string for milliseconds. – epascarello Aug 28 '19 at 19:36
  • You code is just showing the same date over and over again. There is no calculation. – epascarello Aug 28 '19 at 19:37
  • "september 15, 1986 14:29:00" is not a format supported by ECMAScript, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) You should be doing `Date.now() - new Date(1986, 8, 15, 14, 29)`. – RobG Aug 28 '19 at 21:39

2 Answers2

0

To get the milliseconds since your birth, you have to subtract your birth time from the current time. You're just showing the milliseconds from the epoch to your birth time every time you call the function.

function myBirthday(id) {
  birthday = new Date('september 15, 1986 14:29:00')
  milliseconde = new Date().getTime() - birthday.getTime()
  if(milliseconde<10){
    milliseconde = "0"+milliseconde
  }
  resultat = milliseconde+ ' millisecondes ce sont écoulées depuis ma naissance'
  document.getElementById(id).innerHTML = resultat
  setTimeout('myBirthday("'+id+'");','1000')
  return true;

}

myBirthday("output");
<div id="output"></div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You need to deduct your birthday milliseconds from the current date milliseconds:

var birthday = new Date('September 15, 1986 14:29:00');
var now = new Date();
var difference = now - birthday;
Kim T
  • 5,770
  • 1
  • 52
  • 79