ArticleZip > Function To Get Yesterdays Date In Javascript In Format Dd Mm Yyyy Duplicate

Function To Get Yesterdays Date In Javascript In Format Dd Mm Yyyy Duplicate

Are you looking to work with dates in your JavaScript code? Need a function to get yesterday's date in a specific format? You're in the right place! Let's dive into how you can easily achieve this with JavaScript.

To start off, let's create a function that retrieves yesterday's date in the format dd mm yyyy. There are a few steps involved, but don't worry, it's simpler than it sounds.

First things first, here's the function you can use:

Javascript

function getYesterdayDate() {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);

  const dd = String(yesterday.getDate()).padStart(2, '0');
  const mm = String(yesterday.getMonth() + 1).padStart(2, '0'); // January is 0!
  const yyyy = yesterday.getFullYear();

  return dd + ' ' + mm + ' ' + yyyy;
}

// Call the function
const yesterdayDate = getYesterdayDate();
console.log(yesterdayDate);

Let's break it down:
1. We start by creating a new Date object, which gives us the current date and time.
2. With `yesterday.setDate(yesterday.getDate() - 1);`, we subtract one day from the current date, giving us yesterday's date.
3. Next, we extract the day (dd), month (mm), and year (yyyy) from the `yesterday` object. We also ensure that the day and month are always two digits using `padStart`.
4. Finally, we return these values in the format dd mm yyyy.

By calling `getYesterdayDate()`, you can store yesterday's date in the specified format in a variable and use it as needed in your code.

This function is versatile and can be easily integrated into your projects. Whether you need to display the date on your webpage, log it for tracking purposes, or perform calculations based on dates, this function has you covered.

It's worth mentioning that JavaScript's built-in Date object provides powerful capabilities for working with dates and times. By leveraging these functionalities, you can manipulate dates efficiently in your applications.

So, the next time you find yourself needing yesterday's date in dd mm yyyy format in your JavaScript project, remember this handy function. It's a simple yet effective solution to your date-related needs.

Feel free to experiment with this function and adapt it to suit your specific requirements. Happy coding!

×