CorreiaD
CorreiaD

Reputation: 51

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.

Upvotes: 1

Views: 36330

Answers (1)

Sherif
Sherif

Reputation: 11943

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');
}

Upvotes: 3

Related Questions