10

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.

Allen More
  • 858
  • 3
  • 14
  • 25
  • just curious: why do you need it? – Iłya Bursov Oct 17 '16 at 21:23
  • 1
    anyway, you can try `$date = new DateTime()->setTimestamp(0);` – Iłya Bursov Oct 17 '16 at 21:27
  • I'm looping through an array of datetimes to get the latest one and need to initialize the variable I'm using to store the current latest datetime to something that is definitely earlier than any of the array's elements. Otherwise, there could arise a case where all of the datetimes occured before the initial value of this variable which would then be incorrectly returned as the latest datetime. – Allen More Oct 17 '16 at 21:32
  • 2
    then I suggest to use null, and constructs like `if ($min==null || $current<$min) $min = $current;` of course change `<` with appropriate method call – Iłya Bursov Oct 17 '16 at 21:39
  • This is a good solution to my problem. Thank you. – Allen More Oct 17 '16 at 21:44

3 Answers3

10

You're pretty close

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

Will give January 1st, 1970

Josh Johnson
  • 10,729
  • 12
  • 60
  • 83
4

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'));
3
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.

jrbedard
  • 3,662
  • 5
  • 30
  • 34