How to get yesterday's date using JavaScript
How do you get yesterdays' date using JavaScript?
Well, first you get the date at the current time (today), then you subtract a day from it:
const today = new Date()
const yesterday = new Date(today)
yesterday.setDate(yesterday.getDate() - 1)
today.toDateString()
yesterday.toDateString()
We use the setDate()
method on yesterday
, passing as parameter the current day minus one.
Even if it’s day 1 of the month, JavaScript is logical enough and it will point to the last day of the previous month.
→ Get my JavaScript Beginner's Handbook
I wrote 21 books to help you become a better developer:
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- Svelte Handbook
- CSS Handbook
- Node.js Handbook
- Vue Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025