Date Arithmetic in PHP

前端 未结 4 2369
闹比i
闹比i 2020-12-18 18:49

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 (
4条回答
  •  悲&欢浪女
    2020-12-18 19:20

    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.

提交回复
热议问题