user1471980
user1471980

Reputation: 10626

how do you get current day's starting time and the most current time in milliseconds

Need to get the curent time and 00:00 in the morning in milliseconds? I need to do this automatically every day, current starting morning (00:00:00) and current time in milliseconds? Has anyone done something like this?

Upvotes: 2

Views: 318

Answers (3)

m_vdbeek
m_vdbeek

Reputation: 3774

This works :

function millisecondDiff(myDate) {
  var midnightDay = myDate.getUTCDate();
  var midnightMonth = myDate.getUTCMonth() + 1;
  var midnightYear = myDate.getUTCFullYear();
  var midnightMilliseconds = new Date(midnightYear + '/' + midnightMonth + '/' + midnightDay).getTime();
  return new Date().getTime() - midnightMilliseconds;
}

var millisSinceMidnight = millisecondDiff(new Date());
console.log(millisSinceMidnight + ' ms');
console.log((millisSinceMidnight / 1000) + ' s');
console.log((millisSinceMidnight / (1000 * 60)) + ' min');
console.log((millisSinceMidnight / (1000 * 60 * 60)) + ' h');

Upvotes: 1

rink.attendant.6
rink.attendant.6

Reputation: 46218

// Current time
var date = Date.now();

// Since this morning
var date2 = new Date();
date2.setHours(0);
date2.setMinutes(0);
date2.setSeconds(0);
date2.setMilliseconds(0);

See jsFiddle

Upvotes: 0

sushain97
sushain97

Reputation: 2802

To get the current time in milliseconds since epoch (any of these work):

Date.now()
new Date().valueOf()
new Date().getTime()

To get 00:00:00

var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0)
d.valueOf(); // or d.getTime()

Upvotes: 0

Related Questions