PHP Date Examples: compare 2 dates, last day of the month, current date and time

This article contains various tips for using date in PHP.

Get current date and time with defined format

print date("Y-m-d H:i:s");
print date("m-d-Y");

Starting from PHP 5.2, we can use DateTime class

$timezone = new DateTimeZone('EDT');
$datetime = new DateTime();
$datetime->setTimezone($timezone);
print $datetime->format('Y\-m\-d\ h:i:s');

Get current timestamp

print time();

Convert date time string to timestamp

print strtotime(date('Y-m-d H:i:s'));

Compare date time

1. Convert all to timestamp then compare them as number.

if ( strtotime('2020-01-05') > strtotime(date('Y-m-d', mktime(0, 0, 0, 1, 5, 2020))) )
   // do something

2. Convert all to DateTime object then compare

if (new DateTime('2020-01-05') < new DateTime()){
	echo 'Left is smaller';
}

Get the last day of a month

PHP date() function can return the number of days in the month of a given date. Just use “t” when providing format to the function.

$d = "2020-12-01";
echo date("t", strtotime($d)); //output: 31

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close