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

To use the subhours function from date-fns in JavaScript, you must first install the date-fns library using a package manager such as npm or yarn.

npm install date-fns

Once installed, you can import the subhours function and use it in your code:

index.tsx
import { subHours } from 'date-fns';

const date = new Date();
const hoursToSubtract = 2;

const newDate = subHours(date, hoursToSubtract);

console.log(newDate);
// Outputs: Two hours earlier than the current date and time
224 chars
10 lines

In this example, we imported the subHours function from the date-fns library, created a new Date instance, specified the number of hours to subtract (2), and passed these arguments to the subHours function. The subHours function returns a new Date instance with the specified number of hours subtracted from the original date object.

You can also use the subhours function in TypeScript using the same approach. Just make sure to include the appropriate type definitions for the library in your project.

gistlibby LogSnag