how to use the subhours function from the date-fns library in typescript

To use the subhours function from the date-fns library in TypeScript, you first need to install the library:

npm install date-fns
21 chars
2 lines

Once installed, you can import the subHours function from the date-fns module and use it as follows:

import { subHours } from "date-fns";

// subtract 2 hours from the current date and time
const date = new Date();
const newDate = subHours(date, 2);

console.log(newDate); // Output: 2021-09-06T07:15:52.423Z
208 chars
8 lines

The subHours function takes two arguments - the date or timestamp to subtract hours from, and the number of hours to subtract. In the example above, we subtracted 2 hours from the current date and time.

You can also pass a timestamp as the first argument and use the Date constructor to convert the result back into a Date object:

import { subHours } from "date-fns";

const timestamp = 1630912503000; // represents 2021-09-06T09:28:23.000Z
const newDate = new Date(subHours(timestamp, 2));

console.log(newDate); // Output: 2021-09-06T07:28:23.000Z
219 chars
7 lines

As shown above, the subHours function can be used with both Date objects and timestamps, and returns a new date or timestamp that is the specified number of hours earlier.

gistlibby LogSnag