Php - get date

In database table, there is two rows, registerDate and activeTo. Let’s say that the registerDay is ‘2/15/2020’ and activeTo is ‘2/15/2021’, is possible to actually calculate without manually writing activeTo to the database?

Yes there are umpteen different ways depending on how the dates are stored in the table and how they are used.

Beware there are different dateTime formats and “02/15/2020” and “15/02/2020” depending on the time zone:

PHP Online Manual for date(…) function

(https://www.php.net/manual/en/function.date.php

I prefer storing the table dateTime as a Unix Time Stamp because the date can be easily rendered using the PHP date(…) functin and passing the Unix time stamp:

<?php 
declare(strict_types=1);

// seconds * minutes * hours/day * days per year
   $secsPerYear = 60 * 60 * 24 * 366; 

echo '<br>$secPerYear ==> ' ,
  $secsPerYear;

echo '<br>$today ==> ' ,
  $today = date('l, jS F Y \G\M\T T - e') ;

echo '<br>$plusyear ==> ' ,
  $plusyear  = date('l, jS F Y ', time() + $secsPerYear) ;

$dd = '2/15/2020';

  $oDate = date_create($dd, timezone_open('Pacific/Nauru'));
  $oDate = date_create($dd, timezone_open('America/Chicago'));

echo '<pre>'; 
  print_r($oDate); 
echo '</pre>';

echo '<br>$newDate ==> ',
  date_format($oDate, 'Y-m-d H:i:sP') . "\n";

Output:

$row['registerDay'] = '2/15/2020'; // Normally this would come from the database

$registerDay = DateTimeImmutable::createFromFormat('m/d/Y', $row['registerDay']);

$activeTo = $registerDay->add(new DateInterval('P1Y')); // P1Y = 1 Year

See https://repl.it/repls/GeneralTightDisassembly for a runnable example.

1 Like

If you’re going this route (which I don’t recomment, the OOP way is much nicer) it should be

// date('L') = 1 when the current year is a leap year, 0 when it's not.
// Note that this assumes that the `registerDay` in the database is
// in the current year. If it's not then this calculation may well
// be incorrect.
$secsPerYear = 60 * 60 * 24 * (365 + date('L'));

UPDATE: added parentheses

2 Likes

You need some parenthesis there, Remon. Remember your order of operations!

Good call! I’ve added them.