how to use the roundtonearestminutes function from date-fns in javascript

To use the roundToNearestMinutes function from date-fns, you first have to install the library date-fns using npm or yarn

npm install date-fns
21 chars
2 lines

or

yarn add date-fns
18 chars
2 lines

Then, you can import the roundToNearestMinutes function and use it in your code as shown below:

index.tsx
const { roundToNearestMinutes } = require('date-fns');

const currentTime = new Date();
const roundedTime = roundToNearestMinutes(currentTime, { nearestTo: 15 });

console.log(`Current Time: ${currentTime}`);
console.log(`Rounded Time: ${roundedTime}`);
254 chars
8 lines

This code will output something like:

index.tsx
Current Time: Fri Sep 10 2021 22:28:53 GMT+0800 (China Standard Time)
Rounded Time: Fri Sep 10 2021 22:30:00 GMT+0800 (China Standard Time)
140 chars
3 lines

In this example, we import the roundToNearestMinutes function from the date-fns library and use it to round a given Date object to the nearest 15 minutes. The roundToNearestMinutes function takes two arguments - the date object to be rounded, and an options object that specifies the nearestTo value in minutes (which defaults to 1 if not provided).

gistlibby LogSnag