PHP: Help with this date formatting

2019-02-20 02:22发布

I have an application I'm building with CodeIgniter. I have records in a SQL Server DB which have datetime fields.

I'm querying these records from dates entered into a textfield in the m/d/Y. This corresponds to the date format in the db.

Unfortunately I'm in the UK! So I want to enter dates in like d/m/Y. So I need to capture this, format it into the appropriate format and then validate it.

Here's the code in using to format:

    $datestring = "%m/%d/%Y";
    if(isset ($_POST['from_date']) AND isset ($_POST['to_date'])){
        $from = mdate($datestring, strtotime($_POST['from_date']));
        $to = mdate($datestring, strtotime($_POST['to_date']));

I'm using mdate from the CI date helper but it's pretty much the same as date() I think.

If I enter the data 13/12/2010 then post the form and dump the new date it comes out as

string(10) "02/06/2011"

How'd this happen?

Can someone lend a hand? :D

Billy

2条回答
小情绪 Triste *
2楼-- · 2019-02-20 03:10

What I would do is explode the date by '/' and make a new date with mktime:

$from = explode('/', $_POST['from_date']);
$from = mktime(0, 0, 0, $from[1], $from[0], $from[2]);
$from = mdate($datestring, $from);
查看更多
祖国的老花朵
3楼-- · 2019-02-20 03:19

The answer is that the European date format uses dashes, not slashes.

According to the manual:

Note:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

Using a correct format works like a charm:

// American format
//

$_POST['from_date'] = "02/06/2011";    
$yankeeTimestamp = strtotime($_POST['from_date']);

// European format
//

$_POST['from_date'] = "06-02-2011";    
$euroTimestamp = strtotime($_POST['from_date']);

echo date("m/d/Y", $yankeeTimestamp); // returns 02/06/2011
echo date("m/d/Y", $euroTimestamp); // returns 02/06/2011
查看更多
登录 后发表回答