How to calculate time from now to tomorrow 6 am?

Hi there,

I've been reading the post on How to calculate time difference now a bit and would like to calculate the number of hours from now until 6 am tomorrow morning.

I need that to know, when to start the charging of my car based on changing energy price but so that charging is finished by 6 am tomorrow morning.

I know (or can calculate) when the cheapest set of hours comes up, but sometimes this is not so that the charging will be done by 6.

My biggest problem is to create this timestring for tomorrow 6 am automatically in a function node to use it then to calculate the remaining time.

There is a soultion out there but it's clearly not in my brain yet :slightly_frowning_face:.

Any help is highly appreciated.

Takes a bit of playing with the Date object. The trick is to get the timestamp which is in millisecs since midnight Jan 1st 1970, and then round that to the previous midnight timestamp. That gets you to a fixed point you can then add a fixed offset to get to 6am tomorrow.

// Get current time in millisecs since Jan 1st 1970
var now = Date.now();

// Calculate the timestamp of midnight at the *start* of today:
var tstamp = Math.floor(now/86400000)*86400000;

// Add on 30 hours from last midnight to get to 6am tomorrow
tstamp += 108000000;

// Calculate delta between timestamps
var delta = tstamp - now;

// Calculate how many hours that is:
var hours = delta / 3600000;

This won't handle daylight savings time changes - so twice a year it'll either be an hour over or an hour short.

Won't that be in UTC? I think you may need to add on the timezone offset.
In fact I think you need to take adjust now for timezone to get it into local time first, then do the maths.

Ah yes of course. The downside of living in GMT is I always forget to account for other timezones :slight_smile:

1 Like

Install moment.js, add moment:require('moment') to functionGlobalContext in Node-RED's settings.js, and use moment library to calculate the time, for example:

moment = global.get('moment');

var now = moment();
var tomorrow_6_am = moment().startOf('day').add(1, 'days').add(6, 'hours');

msg.payload = tomorrow_6_am.diff(now, 'hours');

return msg;
1 Like

As I said,
there is at least one solution!

Thanks to all contributors.

Plus of course do you actually want the time to 6am tomorrow, which is what you have asked for, or do you want the time to the next 6am? So at 2am do you want 4 hours or 28?

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