How To Get Yesterday’s Date in PHP
In this tutorial, we will learn how to get yesterday’s date using PHP, yes there are many ways to get yesterday’s date in PHP but here we want to make this tutorial easy to understand for you and learn different ways very easily.
So, I am going to make this tutorial interesting for you and I hope you also you are excited to see how we can fetch yesterday’s date and this functionality is useful to include in your projects.
Get yesterday’s date in PHP
So, here I will be using three different functions to get yesterday’s date. you can make use of any one of the functions according to your understanding. Hope you like this tutorial and do comment on your experience and any query if you have.
Three ways for getting yesterday’s date in PHP are:
- time().
- strtotime().
- mktime().
Using time() function in PHP
In PHP time() function is a built-in function and provides us with the timestamp of the actual current time and we can make use of this to get yesterday’s date in PHP using this function.
So, time() returns the current timestamp, to get yesterday’s timestamp we can simply subtract it from its value.
Sample code:
<?php echo date('d M y', time() - 60 * 60 * 24); ?>
Output:
02 JUN 22
Using strtotime() function
In PHP strtotime() is built-in function and we can make use of it for finding yesterday’s date in PHP, this function simply converts English textual date and time into a Unix time stamp.
We can simply do this by passing yesterday’s as a parameter in function or passing -1 days in function.
Sample code:
<?php echo date('d.m.Y',strtotime("-1 days")); ?>
Output:
02.06.2022
Sample code:
<?php echo date('d M Y',strtotime("yesterday")); ?>
Output:
02 Jun 2022
Using mktime() function
In PHP mktime() is built-in function and return UNIX timestamp for a given date. This function takes 6 parameters as an argument in it.
Syntax:
mktime(hour, minute, second, month, day, year)
All 6 arguments are not necessary here. We will be more clear through example.
Sample code:
<?php $month = date("m"); $date = date("d"); // Today's date $year = date("Y"); echo date('d-m-Y', mktime(0,0,0,$month,($date-1),$year)); ?>
Output:
02-02-2022
Also read: Set default timezone in PHP | date_default_timezone_set()
Leave a Reply