开发者

PHP: Help with this date formatting

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 开发者_C百科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


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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜