Php Convert Date To "blank" Days/hours/seconds Ago
Solution 1:
You should always save your dates in MySQL's datetime format (YYYY-MM-DD). This allows you to easily take advantage of MySQL's built in date functionality. Storing it in any other format means (potentially a lot) more work for you when you want to do more then just display those values.
To accomplish what you want to do with PHP you would DateTime()
(based on this answer):
$datetime1 = new DateTime($firstDate);
$datetime2 = new DateTime($secondDate);
$interval = $datetime1->diff($datetime2);
if ($interval->days <= 7)
{
$elapsed = $interval->format('%y years, %m months, %a days, %h hours, %i minutes, %S seconds');
$elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,', ' 0 hours,', ' 0 minutes,'), '', $elapsed);
$elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ', ' 1 hours, ', ' 1 minutes'), array('1 year, ', '1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'), $elapsed);
echo$elapsed;
}
else
{
echo$firstDate;
}
$datetime1 = new DateTime($firstDate);
$datetime2 = new DateTime($secondDate);
These lines create DateTime()
objects with their respective dates.
$interval = $datetime1->diff($datetime2);
This lines subtracts the second date from the first and returns the difference as a DateInterval()
object.
if ($interval->days > 7)
This line checks to see seven or more days have elapsed between the two dates. If so the first code block is executed. If not, the first date is printed out.
$elapsed = $interval->format('%y years, %m months, %a days, %h hours, %i minutes, %S seconds');
$elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,', ' 0 hours,', ' 0 minutes,'), '', $elapsed);
$elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ', ' 1 hours, ', ' 1 minutes'), array('1 year, ', '1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'), $elapsed);
echo$elapsed;
This code block just takes the date difference between the two dates (a DateInterval()
object) and formats it in the format you requested. The second lines removes any periods of time that have no values (i.e. 0 months) and removes them from the string. The third line takes any periods with one value (i.e. 1 months) and trims off the unnecessary 's' at the end (i.e. 1 months becomes 1 month).
Post a Comment for "Php Convert Date To "blank" Days/hours/seconds Ago"