如何根据年和月计算日期,反之亦然[关闭]

I want the month os last year when user selects in the month of January.

For example: if today is 01-01-2018 (first month of 2018) and the user selects December or 'November', I want 01-12-2017 to 31-12-2017(November or December of 2017).

if today is 15-12-2018 (selects December in 2018), and user selects December, I want 01-12-2018 to 31-12-2018 (want December of 2018).

This can be done with strtotime() and timestamps (expressed in seconds, not days of course), but here's a method using DateTime objects:

function get_thirty_days(\DateTime $date_in, int $days = null) {
    $days = $days ?? 30;
    $date_out = $date_in->add(new \DateInterval(sprintf('P%dD', $days)));
    $dates = [];

    while ($days) {
        $dates[] = $date_out
            ->sub(new \DateInterval('P1D'))
            ->format('Ymd')
        ;

        $days--;
    }

    return $dates;
}

Then, all you have to do is have a valid \DateTime object to pass in and does the offset for you:

get_thirty_days(new \DateTime()); // An array of dates, largest first, 30 days.
get_thirty_days(new \DateTime('2017-01-15'), 40); // An array of 40 dates, starting from...
array_reverse(get_thirty_days(new \DateTime('2017-01-15'), 10));

https://3v4l.org/5QjEr


Here is a method using timestamps only:

get_thirty_days((new \DateTime())->getTimestamp());

function get_thirty_days(int $start_date_ts, int $days = null) {
    $days = $days ?? 30;
    $dates = [];

    while ($days--) {
        $dates[] = date('Y-m-d', $start_date_ts + ($days * (60 * 60 * 24)));
    }

    return $dates;
}

https://3v4l.org/UXPA0

I would use the Carbon package for something like this, just because it makes this job so easy and I have it already included in 90% of my projects.

The code would look something like this (untested):

function getDays($month) {
   $date = Carbon::now()->setMonth($month)->startOfMonth();
   $days = [];
   while($date->month == $month) {
      $days[] = $date->toDateString(); // or whatever format suits you
      $date->addDay();
   }
   return $days;
}

Not much to explain I guess, the intuitive Carbon API makes the code speak for itself.

use DateTime class to make operations on dates , it's much easier

Anwser to your question is http://php.net/manual/pl/datetime.diff.php

<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>