Javascript Date get number of seconds passed for today

Introduction

We would like to write a function getSecondsToday().

It returns the number of seconds from the beginning of today.

For instance, if now were 10:00 am, and there was no daylight savings shift, then:

getSecondsToday() == 36000 // (3600 * 10)

Hint

To get the number of seconds, generate a date using the current day and time 00:00:00, then substract it from 'now'.



function getSecondsToday() {
  let now = new Date();

  // create an object using the current day/month/year
  let today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

  let diff = now - today; // ms difference
  return Math.round(diff / 1000); // make seconds
}

console.log( getSecondsToday() );

An alternative solution would be to get hours/minutes/seconds and convert them to seconds:

function getSecondsToday() {
  let d = new Date();
  return d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
}
console.log( getSecondsToday() );//from w  ww . jav  a  2s  . com



PreviousNext

Related