How to start date with 0 seconds and 0 milliseconds with date javascript

hello,
I want to display time on x-axis with the date object in javascript. Right now, the date is inserted and time is displayed with current time is working. But in my case I want to start the graph with 0 seconds and 0 milliseconds and then up-counting. how can i do this? I tried the following:

let today = new Date();
today.setSeconds(0);
today.setMilliseconds(0);

function dataEvent() {
  //let today = new Date();
  let t = today.getSeconds() + ":" + today.getMilliseconds();
    data.labels.push(t);
}

thanks

Just setup your date in the function and that should work fine. Here is a function that returns the current date with the seconds and milliseconds set to zero. It then returns the object. You can then pull out the seconds and milliseconds or whatever you want to do with it.

function dataEvent() {
  let today = new Date();
  today.setSeconds(0);
  today.setMilliseconds(0);
  return today;
}

Here is a pen to show you the output…

hi,
it will return full date(year, hours…) but i want only seconds and milliseconds like 00:00 as the starting of the real time streaming, and then increasing like 00:01, 00:02 etc, how can i do that?

Consider using the Date valueOf() method to get the number of milliseconds since the start of year 1970.

This CodePen displays the time elapsed since the web page loaded when you click ‘Click me’ (which you can click more than once).

I am not sure that’s going to help much in labelling an ‘x’ axis.

hi,
when i click on it nothing happens!

You cannot show seconds and milliseconds in format 00:00 as milliseconds will have 3 digits.

Also I don’t understand why you need a date format if you want to display milliseconds. Just take a number and increment it and format it to 00:000 in the output. Like

Let milliseconds=0;
while(milliseconds++ < 5000)
    console.log(Math.round(milliseconds / 1000)+“:“+(milliseconds % 1000));

When I click the “Click me” button I get an alert box showing the elapsed time.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.