How to Calculate Yesterday’s Date in TypeScript

While building a feature for a client project, I needed to log data from the previous day. That meant figuring out how to get yesterday’s date in TypeScript. It sounds simple, but it needs to be done right, especially when dealing with time zones or edge cases.

In this tutorial, I’ll explain how to calculate yesterday’s date in TypeScript, with a clear example you can adapt for your own scheduling, logging, or reporting needs.

Why TypeScript for Date Manipulation?

TypeScript is a powerful superset of JavaScript that adds static typing to the language. This helps catch errors at compile-time, making your code more robust and easier to maintain. When dealing with dates, TypeScript’s type system can help ensure that your date calculations are correct and prevent common pitfalls.

Prerequisites

Before diving into the code, ensure you have the following:

  • Node.js is installed on your machine
  • A basic understanding of TypeScript and JavaScript
  • A TypeScript project set up (you can use tsc –init to initialize a TypeScript project)

Check out: Get Tomorrow’s Date in TypeScript

Getting Started

First, create a new TypeScript file named dateUtils.ts. This file will contain all the functions we need to calculate yesterday’s date.

Step 1: Importing the Date Object

To work with dates in TypeScript, we use the built-in Date object. Let’s start by importing the necessary modules and setting up our function.

// dateUtils.ts

export function getYesterdayDate(): Date {
    const today = new Date();
    today.setDate(today.getDate() - 1);
    return today;
}

Output:

Calculate yesterday date in typescript

In this function, we create a new Date object representing the current date and time. We then use the setDate method to subtract one day from the current date. The getDate method retrieves the day of the month, and setDate sets the day of the month.

Step 2: Formatting the Date

Often, we need to format the date in a specific way. For instance, you might want to display the date as MM/DD/YYYY. Let’s add a function to format the date.

export function formatDate(date: Date): string {
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const year = date.getFullYear();
    return `${month}/${day}/${year}`;
}

In this function, we use getMonth, getDate, and getFullYear to extract the month, day, and year from the Date object. We then pad the month and day with leading zeros if necessary, and return the formatted date string.

Step 3: Combining the Functions

Now, let’s combine these functions to get and format yesterday’s date.

// dateUtils.ts

export function getFormattedYesterdayDate(): string {
    const yesterday = getYesterdayDate();
    return formatDate(yesterday);
}
console.log("Formatted yesterday's date is:", getFormattedYesterdayDate());

Output:

Get yesterday date in Typescript

This function calls getYesterdayDate to get yesterday’s date and then formats it using formatDate.

Real-World Example

Let’s say you’re developing a weather application for Los Angeles. You want to display the weather data for yesterday. Here’s how you can use the functions we created.

// app.ts

import { getFormattedYesterdayDate } from './dateUtils';

const yesterday = getFormattedYesterdayDate();
console.log(`Yesterday's date was: ${yesterday}`);

When you run this code, it will output yesterday’s date in the MM/DD/YYYY format.

Handling Time Zones

When working with dates, it’s crucial to consider time zones, especially if your application serves users in different parts of the USA. JavaScript’s Date object uses the local time zone of the environment where the code is running. If you need to work with a specific time zone, you can use libraries like moment-timezone or the newer Intl.DateTimeFormat API.

Using moment-timezone

First, install the library:

npm install moment-timezone

Then, you can use it to calculate yesterday’s date in a specific time zone:

// dateUtils.ts

import moment from 'moment-timezone';

export function getYesterdayDateInTimeZone(timeZone: string): string {
    const yesterday = moment().tz(timeZone).subtract(1, 'day');
    return yesterday.format('MM/DD/YYYY');
}

Now, you can use this function to get yesterday’s date in New York time:

// app.ts

import { getYesterdayDateInTimeZone } from './dateUtils';

const yesterdayInNY = getYesterdayDateInTimeZone('America/New_York');
console.log(`Yesterday's date in New York was: ${yesterdayInNY}`);

Output:

how to get yesterday date in Typescript

Conclusion

In this tutorial, we’ve covered how to calculate yesterday’s date in TypeScript and format it for display. We’ve also discussed handling time zones using the moment-timezone library. By following these steps, you can ensure that your date calculations are accurate and reliable, making your TypeScript applications more efficient.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.