S
S
suhuxa12018-04-03 12:39:21
PHP
suhuxa1, 2018-04-03 12:39:21

How to solve the riddle with the date?

They gave me a project to lead, and there the date works through the DateTime (php) library. There is such a mechanism - if the date is transmitted through the get, then the date object is formed from it, otherwise the date is the current day.

$date = $request->getParam('date');
        if (!empty($date)) {
            $date = DateTime::createFromFormat('Y-m-d', $date);
        } else {
            $date = new DateTime;
        }

Everything seems to work fine, no problems. But I need to check the records of the previous day. That is, if the date is not transferred to the GET, then the entries are for yesterday, and if transferred, then the entries are the day before the date that was transferred. I read how it is done, the simplest is like this:
$my_date = strtotime($date->date);
        $my_date = strtotime('-1 day', $my_date);
        $my_date = date('Y-m-d', $my_date);

Where $date is the data object formed above, the result looks like this:
DateTime Object ( [date] => 2018-04-01 15:30:00.000000 [timezone_type] => 3 [timezone] => Asia/Omsk )

And everything seems to work, but here's what's interesting. If I specify as specified, the result is:
1969-12-31
But! If before this code I write the output of an object with a date, then MIRACLE, the result is as I need:
2018-03-31
spoiler
Это как так получается? Приложил наглядные скрины:
4b4b1c82b3.jpg3b59c2be97.jpg5e7a11fdeb.jpg893f7419d6.jpg

what miracles? And how to solve it? Thanks

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2018-04-03
@Minifets

Have you tried that?

/** @var \DateTime $date */
$date->modify('-1 day');

A
Alexey Hog, 2018-04-03
@Skiphog

Create a date immediately "yesterday"

///...
} else {
    $date = new DateTime('yesterday');
}

B
Boris Korobkov, 2018-04-03
@BorisKorobkov

First, it's a very bad idea to use the same variable for both string and object.
Secondly, it is necessary to check the correctness of the date. If it came, but not in the format, then an object with a zero date (the beginning of the unix epoch, that is, 1970-01-01) may be created
. Third, specify a test-case with your problem. So that you can run it for yourself to check.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question