Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the earliest possible datetime in php?

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.

like image 525
Allen More Avatar asked Oct 17 '16 21:10

Allen More


People also ask

How can I get first date and date of last month in PHP?

php echo 'First Date = ' . date('Y-m-01') . '<br />'; echo 'Last Date = ' . date('Y-m-t') .

How can I get previous date from DateTime in PHP?

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.

How do I get the start of the week in PHP?

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.


3 Answers

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.

like image 96
jrbedard Avatar answered Oct 31 '22 11:10

jrbedard


You're pretty close

$date = (new DateTime())->setTimestamp(0);

Will give January 1st, 1970

like image 42
Josh Johnson Avatar answered Oct 31 '22 10:10

Josh Johnson


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'));
like image 4
Doug Wilbourne Avatar answered Oct 31 '22 10:10

Doug Wilbourne