How to handle date and time using PHP?

I need to do some more complicated calculations with time and date values ​​from my MySQL database with PHP.

I need to add or subtract different values ​​from a specific date.

For instance:

  • Substracting 1 Month
  • Substracting 30 Days
  • Substracting 4 Weeks
  • Adding 4 months
  • Adding 3 months
  • Adding 90 days
  • Addition 2 years

Please note that there is a difference between subtracting 1 month, 4 weeks or 30 days.

What is the preferred way to do this? Is there a smart library or can I do this using native PHP functions?

+5
source share
10 answers

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";
?>

, :

echo strtotime("+1 week",$timestamp)
+7

PHP5 DateTime DateInterval.

$now = new DateTime();

// 30 days ago
$now->sub(new DateInterval("P30D");

// 1 week ago
$now->sub(new DateInterval("P1W");

// 2 years from now
$now->add(new DateInterval("P1Y");

.

+5

PHP 5.2 DateTime. :

$date = new DateTime; // now
$date->modify('1 month ago');
echo $date->format('Y-m-d');

sintax.

+4

PHP strtotime .

:

// 1 month ago
$date = strtotime('-1 month');

// 30 days ago
$date = strototime('-30 days');
+1
<?php
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>

$date "2000-01-11".

date_sub .

:

http://www.php.net/manual/en/datetime.add.php http://www.php.net/manual/en/datetime.sub.php

+1

strtotime(). http://php.net/manual/en/function.strtotime.php

, , , .

strtotime('+1 day', mktime(0, 0, 0, 7, 1, 2000));
0

Pear Date. , . , .

http://pear.php.net/Date

-, ..

0
0

here is another suggestion. if you want to manipulate information from mysql try using the date / time functions provided by mysql here

0
source

All Articles