This should be an easy one but I just can't find the answer.
I have an input field in which the user enters his birthay date (DD.MM.YYYY) and with strtotime() I insert it into integer field in MySQL because it's faster that datetime (and I have a lot of records).
But obviously there will be users older than 1.1.1970 so the timestamp would be zero.
On the webpage I want to show how old is the user. So if he is born in 1960 he would be 51 years old.
I know that I could change MySQL field to DATETIME but still the PHP would be the one to calculate the age of user and it uses UNIX timestamp.
So, how should I organize it?
Thanks!
You should use the DateTime object when handling dates and times in PHP. It is very flexible when parsing date formats, it can calculate the difference between two dates and it has no 1970 or 2038 problem.
You should use MySQL DATETIME, calculate in sql query . use php date() function to convert to mysql DATETIME when you save into database
You must use DateTime object, You can see one sample code here:
<?php
$date = new DateTime("1960-05-06");
$timestamp = $date->getTimestamp();
echo $timestamp; //-304707600
echo "\n";
$date = new DateTime();
$date->setTimestamp($timestamp);
$birthday = $date->format("Y-m-d");
echo $birthday; //1960-05-06
echo "\n";
echo date("Y") - $date->format("Y"); //55 years old for now (2015)
?>
Output:
-304732800
1960-05-06
55
Online test here: https://ideone.com/sKjBWS