Using getTime() method
Imagine you are building a service that allows users to subscribe to a premium plan that lasts 15 days. When a user subscribes, you need to calculate the date when their subscription will expire so that you can restrict their access to the premium features or ask for renewal after that date. The code below shows you how to do that:
// Get the current date const currentDate = new Date(); // Calculate the expired date // By adding 15 days to the current date const expiredDate = new Date(currentDate.getTime() + 15 * 24 * 60 * 60 * 1000); // Log current date and expired date in friendly format console.log("Current date: ", currentDate.toDateString()); console.log("Expired date: ", expiredDate.toDateString());
15 * 24 * 60 * 60 * 1000 is exactly the number of milliseconds in 15 days.
Current date: Thu Feb 16 2023 Expired date: Fri Mar 03 2023
Using getDate(), setDate(), getHours(), setHours()
The example below calculates a time in the future that is 5 days, 9 hours, 30 minutes, and 30 seconds away:
// Get the current date const date = new Date(); console.log('today: ', date.toLocaleString()); // add 5 days date.setDate(date.getDate() + 5); // continuing adding 9 hours date.setHours(date.getHours() + 9); // continuing adding 30 minutes date.setMinutes(date.getMinutes() + 30); // continuing adding 30 seconds date.setSeconds(date.getSeconds() + 30); // print the result console.log('result: ', date.toLocaleString());
today: 2/16/2023, 7:05:24 PM result: 2/22/2023, 4:35:54 AM
In the code above, we have continuously mutated the original date object by adding days, hours, minutes, and seconds to it. The methods used are:
- getDate() and setDate()
- getHours() and setHours()
- getMinutes() and setMinutes()
- getSeconds() and setSeconds()
In addition, you can use the setMilliseconds() method and setMilliseconds() method if needed. However, very rarely do we have to care about these microscopic amounts of time.