Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Arithmetic in PHP

Tags:

Is there a PHP function I can use to do something like the following:

  • Get the date 6 months ago (e.g. now - 6 months)?
  • Get the date 2 years from now (e.g. now + 2 years)?
like image 978
StackOverflowNewbie Avatar asked Nov 23 '11 00:11

StackOverflowNewbie


People also ask

What is the use of date () function in PHP?

The date() function formats a local date and time, and returns the formatted date string.

What is data type of date in PHP?

PHP Date/Time IntroductionThe date/time functions allow you to get the date and time from the server where your PHP script runs. You can then use the date/time functions to format the date and time in several ways.

How can I get current date and time in PHP?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.


1 Answers

Yes, there is: strtotime():

  1. 6 months ago: strtotime("-6 months");
  2. 2 years: strtotime("+2 years");

These will return Unix timestamps. So you might want to put the result into date() or localtime() or gmtime().

Please do not try to subtract 6 months or add 2 years of seconds to time(). This does not take into account things like daylight saving or leap seconds and still gives you a value in seconds which is unlikely to be the precision you need. Let the library functions do it.

like image 103
staticsan Avatar answered Sep 17 '22 21:09

staticsan