Date() Format, Differences Between D-M-Y and D/M/Y

this is my first post so sorry if i do something wrong. Well I got this code

$min=date('d-m-Y');

$max=date ('31-12-2015');


function rand_date($min, $max) {


    $min_epoch = strtotime($min);
    $max_epoch = strtotime($max);

    $rand_epoch = rand($min_epoch, $max_epoch);

    return date('d-m-Y H:i:s', $rand_epoch);
}

echo rand_date($min, $max);//return 04-12-2015 07:48:22`

It works, but the problem comes when I use this with the format than i need (d/m/Y)

$min=date('d/m/Y');

$max=date ('31/12/2015');


function rand_date($min, $max) {


    $min_epoch = strtotime($min);
    $max_epoch = strtotime($max);

    $rand_epoch = rand($min_epoch, $max_epoch);

    return date('d/m/Y H:i:s', $rand_epoch);
}

echo rand_date($min, $max);// Always shows 01/01/1970 01:00:00`.

I need works with this format, so I will be grateful if somebody answer my question.

2

1 Answer

The default interpretation of 31/12/2015 for PHP date/time functions/methods is m/d/Y when using forward-slashes, and d-m-Y or Y-m-d when using dashes, if you check the manual. Which is why something like date('31/12/2015') returns false since there is no 31st month in a year.

Use DateTime::createFromFormat instead to specify your own variations if you must.

Example

$min = new DateTime;

$max = DateTime::createFromFormat('d/m/Y', '31/12/2015');


function rand_date(DateTime $min, DateTime $max) {
    $min_epoch = $min->getTimeStamp();
    $max_epoch = $max->getTimeStamp();

    $rand_epoch = rand($min_epoch, $max_epoch);

    return (new DateTime("@$rand_epoch"))->format('d/m/Y H:i:s');
}
1
David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article