I'm making a major update to my book series and it is taking a lot of time away from writing here.

One of the major changes is moving from local dates to UTC dates. I'm in a situation where I want to load data from a database within a 24 hour range. I have the start time, but need to get the end time. How do you do that in JavaScript?

First, the UTC string is something like this:

view plain print about
12021-05-07T00:01:00.000Z

I can turn that into a JS Date object like this:

view plain print about
1const startDate = new Date('2021-05-07T00:01:00.000Z');

Now, I want to add 24 hours to it. I can use the setDate() method, along with getDate():

view plain print about
1const endDate = new Date('2021-05-07T00:01:00.000Z');
2endDate.setDate(startDate.getDate()+1));

Output both values:

view plain print about
12021-05-07T00:01:00.000Z
22021-05-08T00:01:00.000Z

Boom, now I have the start date and a date representing 24 hours after that. You have to be careful using the setDate(), because it will change your current date value as opposed to create a new one.

Another way to do this is to create the second date entirely based off the values in the first date:

view plain print about
1const startDate2 = new Date('2021-05-07T00:01:00.000Z');
2const endDate2 = new Date(startDate2.getFullYear(), startDate2.getMonth(), startDate2.getDate()+1, startDate2.getHours(), startDate2.getMinutes())

Play with this code over here