Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle date and time with PHP?

I need to do a little bit more complicated calculations with time and date values from my MySQL database with PHP.

I need to add or substract different values from a given date.

For example:

  • Substracting 1 Month
  • Substracting 30 Days
  • Substracting 4 Weeks
  • Adding 4 Month
  • Adding 3 Month
  • Adding 90 Days
  • Adding 2 Years

Please note that there is a difference between substracting 1 Month, 4 Weeks or 30 Days.

What's the preferred way of doing this? Is there any clever library or can I do this with PHP's own functions?

like image 202
Norwald2 Avatar asked Nov 04 '10 20:11

Norwald2


People also ask

How can I insert current date and time in PHP?

php $date=strtotime("tomorrow"); echo date("Y-m-d h:i:sa", $date) . "<br>"; $date=strtotime("next Sunday"); echo date("Y-m-d h:i:sa", $date) . "<br>"; $date=strtotime("+3 Months"); echo date("Y-m-d h:i:sa", $date) .

How can I get current date in YYYY MM DD format in PHP?

date_default_timezone_set('UTC'); echo "<strong>Display current date dd/mm/yyyy format </strong>". "<br />"; echo date("d/m/Y"). "<br />"; echo "<strong>Display current date mm/dd/yyyy format</strong> "."<br />"; echo date("m/d/Y")."<br />"; echo "<strong>Display current date mm-dd-yyyy format </strong>".

How does date work in PHP?

The date function in PHP is used to format the timestamp into a human desired format. The timestamp is the number of seconds between the current time and 1st January, 1970 00:00:00 GMT. It is also known as the UNIX timestamp. The default time zone can also be set programmatically using PHP scripts.

What does time () in PHP return?

The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).


1 Answers

From http://php.net/manual/en/function.strtotime.php

<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>

You can add a second parameter to make it add to given time:

echo strtotime("+1 week",$timestamp)
like image 153
drew Avatar answered Sep 28 '22 00:09

drew