Calculate Epoch Time Using Date

Here’s how to calculate epoch time using the Linux date command.

# Linux
date --date @1561266781
date -d @1561266781
# MacOS
date -r 1561266781

Output is : Sun Jun 23 05:13:01 UTC 2019

Show current epoch time.

date +%s

Output: 1561642643

Comparing Time

Here’s a neat little PHP script that compares a set date/time to the current time. The time() function sets the $now variable to the current Unix timestamp. The strtotime() function converts a date string to a Unix timestamp. The result is assigned to the $setdate variable. The two variables containing Unix timestamps are then compared. A simple if-then statement determines if the date is in the past or future.

date_default_timezone_set('America/Los_Angeles');
$setdate = strtotime("May 9, 2017 12:27PM");
$now = time();
if ( $setdate > $now ) : echo 'Future date'; else : echo 'Past date'; endif;

You may have to change the default timezone if your server is in a different timezone.

Ubuntu Server Timezone

If you want to run a couple of cron jobs, you may need to check if your server is using your timezone. You can determine the server’s timezone by simply typing the system’s date command. You’ll see right away if your server is using the same timezone.

$ date
Sun Apr 23 21:21:24 PDT 2017

If it isn’t, then you need to change it so it’s in sync with cron jobs. To change timezone, run dpkg-reconfigure tzdata. You’ll be asked to choose a region and the nearest city. In this example, I’m picking the Americas/Los Angeles combination. Choose your own region and city.

$ sudo dpkg-reconfigure tzdata
Current default time zone: 'America/Los_Angeles'
Local time is now:      Sun Apr 23 21:24:57 PDT 2017.
Universal Time is now:  Mon Apr 24 04:24:57 UTC 2017.

You may need to restart cron so that the new timezone can take effect.

$ sudo service cron restart