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

To use the startOfYesterday function from date-fns you first need to install the library. You can install it using npm by running the following command in your terminal.

npm install date-fns
21 chars
2 lines

Once installed, you can import the startOfYesterday function and use it in your code.

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

const yesterday = startOfYesterday();

console.log(yesterday);
// Outputs: 2022-01-05T00:00:00.000Z
151 chars
7 lines

The startOfYesterday function returns a new date object set to the start of yesterday (i.e. 12:00:00 AM).

You can also use the function to set the start of yesterday for a specific timezone.

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

const timezone = 'America/New_York';
const yesterday = zonedTimeToUtc(startOfYesterday(), timezone);

console.log(yesterday);
// Outputs: 2022-01-04T05:00:00.000Z
215 chars
8 lines

In the example above, we used the zonedTimeToUtc function from date-fns-tz to convert the startOfYesterday date object to the UTC timezone. We passed in the timezone string as the second argument to zonedTimeToUtc. This returned a new date object set to the start of yesterday in the America/New_York timezone (i.e. 5:00:00 AM UTC).

gistlibby LogSnag