开发者

Storing date values passed by AJAX call in CakePHP

开发者 https://www.devze.com 2023-03-13 20:00 出处:网络
I\'m trying to pass a javascript Date object to a controller that I have in CakePHP via an AJAX call. I had to convert the date object in js before sending it over, cause it wasn\'t being sent.

I'm trying to pass a javascript Date object to a controller that I have in CakePHP via an AJAX call. I had to convert the date object in js before sending it over, cause it wasn't being sent.

startDate = startDate.toUTCString();

What I get in the controller is a string

Wed, 31 Jan 2001 14:01:01 GMT

No problem so far. But now I need to store this value in database which uses a datetime field开发者_运维百科 for this. I noticed Cake uses this array that represents the datetime.

[start_date] => Array
(
    [month] => 06
    [day] => 20
    [year] => 2011
    [hour] => 02
    [min] => 19
    [meridian] => am
)

How can I convert the string that I have earlier to this structure?


You don't need to. Cake just keeps that structure internally, but all it actually needs is a date string that is compatible with your database. So you can just send it a string in the form of 'YYYY-MM-DD' and it will save it.

The best way to do this is to send yourself the JS timestamp instead of the string representation.

var date = new Date();
var timestamp = date.getTime();//this will give you the timestamp

Once you have the timestamp, send it to cake

//assuming you have the timestamp in the variable $timestamp
$formatted_date = date('Y-m-d', $timestamp / 1000); 
//dividing by 1000 because JS timestamps are in miliseconds and PHP uses seconds
$this->data['Model']['start_date'] = $formatted_date;

That's all you need to do.

0

精彩评论

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