0

I want to parse a year into a date format, but it returns still the current year:

$year = $_GET['year']; // p.e. 2020
$start = date ('Y-01-01', strtotime ("$year")); // returns 2023-01-01
$stop = date ('Y-12-31', strtotime ("$year")); // returns 2023-12-31

How get I fix this so it returns 2020-01-01 and 2020-12-31?

So many thanks!

  • 2
    `"$year-01-01"`? – brombeer Jul 18 '23 at 09:23
  • The date format specifier is just a string. So this question is effectively "How do I put a PHP variable into a string", which can be answered by reading the documentation, or by a billion previous posts on the internet. – ADyson Jul 18 '23 at 09:27
  • 1
    Does this answer your question? [PHP - concatenate or directly insert variables in string](https://stackoverflow.com/questions/5605965/php-concatenate-or-directly-insert-variables-in-string) – ADyson Jul 18 '23 at 09:27
  • 1
    The reason it doesn't work as per your attempt is because `strtotime` doesn't accept only the year as a parseable date - again see the documentation: https://www.php.net/manual/en/function.strtotime.php – ADyson Jul 18 '23 at 09:29
  • 1
    So in theory you could write `echo date ('Y-01-01', strtotime ("$year-01-01"));` but as brombeer notes, simply using $year directly in the output is a lot less verbose and doesn't involve any redundant string and date parsing (redundant because you're parsing a format and outputting it in the same format again!) - demo: https://3v4l.org/oSgus – ADyson Jul 18 '23 at 09:31
  • 2
    If you use `date ('Y-01-01 H:i:s', strtotime ("$year"));` you'll get `2023-01-01 20:20:00`, note that your `2020` is considered a time value: `20:20:00` – brombeer Jul 18 '23 at 09:33
  • So many thanks to all of you! The solution of Brombeer works fine! I am very happy :-) – Michaël Thönnissen Jul 18 '23 at 09:47

1 Answers1

-1

You may try this.

$year = $_GET['year']; // p.e. 2020
$start = date('Y-01-01', strtotime("$year-01-01")); // returns 2023-01-01
$stop = date('Y-12-31', strtotime("$year-12-31")); // returns 2023-12-31
imran11439
  • 26
  • 5
  • 2
    Technically this works, of course. But what is the point of all this extra code and and extra processing, when we can just write `$start = "$year-01-01"; $stop = "$year-12-31";` and get exactly the same result? I said this in a comment already. – ADyson Jul 18 '23 at 11:29