publicstaticmain
publicstaticmain

Reputation: 49

Javascript programmatic way to get time in 30 min interval between two date objects

Apologies if the question was worded poorly, what I'm looking for is something like this; say you are given two dates (but all you really care about is the time portion of the date object, not the date), 8 AM and 5 PM, I want to be able to print out the time every 30 mins between the two dates (i.e 8:00AM, 8:30,AM 9:00AM, 9:30AM... 4:30PM, 5PM). Replies are appreciated.

Upvotes: 2

Views: 1957

Answers (2)

nick-w-nick
nick-w-nick

Reputation: 182

If you'd like to perform some sort of operation or run a function (such as logging out the time) every 30 minutes between a range of times, you can use what is known as cron format in combination with a module that can ingest cron values and run functions on a pre-defined schedule.

I suggest the node-cron module.

To run a task every 30 minutes between 8AM and 5PM, in this case printing out the current time, you can create a schedule using cron formatting.

The cron format for every 30 minutes between 8AM and 5PM would look like */30 08-17 * * *.

const cron = require('node-cron');

cron.schedule('*/30 08-17 * * *', () => {
  console.log(new Date().toLocaleTimeString());
});

Upvotes: 2

Spectric
Spectric

Reputation: 31992

You can store the start date and end date in a Date object, then use a while loop to continuously add 30 minutes to the start while the start date is smaller than the end date.

const start = new Date();
start.setHours(8, 0, 0); //8 AM
const end = new Date();
end.setHours(17, 0, 0); //5 PM

while (start <= end) {
  console.log(start.toLocaleString('en-US', {hour: '2-digit', minute: '2-digit'}));
  start.setMinutes(start.getMinutes() + 30);
}

Upvotes: 6

Related Questions