My understanding is that datetimes in php are represented as the number of milliseconds after a certain date (some time in 1960 I think?). How to I construct a datetime that represents the earliest allowable date in php? An example possible syntax would be:
$date = new DateTime(0);
but this doesn't work. Is there some other way to do this?
Thanks for any input.
php echo 'First Date = ' . date('Y-m-01') . '<br />'; echo 'Last Date = ' . date('Y-m-t') .
In PHP time() function is a built-in function and provides us with the timestamp of the actual current time and we can make use of this to get yesterday's date in PHP using this function. So, time() returns the current timestamp, to get yesterday's timestamp we can simply subtract it from its value.
Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date.
echo date('d-m-Y', 0); // outputs: 01-01-1970
epoch 0
gives the unix timestamp 01-01-1970
or 00:00:00 UTC on January 1st 1970.
You're pretty close
$date = (new DateTime())->setTimestamp(0);
Will give January 1st, 1970
I think the smallest and largest dates that the DateTime object will accept are as follows (on a 64 bit machine as of PHP 7.4, demonstrated using PHPUnit). This can be useful in providing default mins and maxes on a date validator for both DateTime as well as Carbon. This answer is also posted in the user contributed notes of the PHP manual page for DateTime::__construct().
If you want to get very precise about it, modify the code below to account for time and timezone.
// smallest date
$input = '-9999-01-01';
$dt = new \DateTime($input);
self::assertEquals($input, $dt->format('Y-m-d'));
$input = '-10000-12-31';
$dt = new \DateTime($input);
self::assertEquals('2000-12-31', $dt->format('Y-m-d'));
// largest date
$input = '9999-12-31';
$dt = new \DateTime($input);
self::assertEquals($input, $dt->format('Y-m-d'));
$input = '10000-01-01';
$dt = new \DateTime($input);
self::assertEquals('2000-01-01', $dt->format('Y-m-d'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With