We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to use builtin types

Hi,

Mongo has many types of date object (for example ISODate()).

For example I have MobileUsers:


/**
 * Class MobileUsers
 */
class MobileUsers extends \Phalcon\Mvc\Collection
{
    /**
     * @var string
     */
    public $user_id;

    /**
     * @var array
     */
    public $devices;

    /**
     * @return string
     */
    public $created_at;

    /**
     * @return string
     */
    public $updated_at;

    public function getSource()
    {
        return "users";
    }

    public function beforeCreate()
    {
        $this->created_at = date('Y-m-d H:i:s');
    }

    public function beforeUpdate()
    {
        $this->updated_at = date('Y-m-d H:i:s');
    }
}

How to use ISODate instead string with ODM?



98.9k
Accepted
answer

I think you can use MongoDate to represent those data types: https://php.net/manual/en/class.mongodate.php

Yeah, I find that ISODate is a kind of Date data type (javascript wrapper)

> ISODate
function (isoDateStr){
    if (!isoDateStr)
        return new Date();

    var isoDateRegex = /(\d{4})-?(\d{2})-?(\d{2})([T ](\d{2})(:?(\d{2})(:?(\d{2}(\.\d+)?))?)?(Z|([+-])(\d{2}):?(\d{2})?)?)?/;
    var res = isoDateRegex.exec(isoDateStr);

    if (!res)
        throw "invalid ISO date";

    var year = parseInt(res[1],10) || 1970; // this should always be present
    var month = (parseInt(res[2],10) || 1) - 1;
    var date = parseInt(res[3],10) || 0;
    var hour = parseInt(res[5],10) || 0;
    var min = parseInt(res[7],10) || 0;
    var sec = parseInt((res[9] && res[9].substr(0,2)),10) || 0;
    var ms = Math.round((parseFloat(res[10]) || 0) * 1000);
    if (ms == 1000) {
        ms = 0;
        ++sec;
    }
    if (sec == 60) {
        sec = 0;
        ++min;
    }
    if (min == 60) {
        min = 0;
        ++hour;
    }
    if (hour == 24) {
        hour = 0;   // the day wrapped, let JavaScript figure out the rest
        var tempTime = Date.UTC(year, month, date, hour, min, sec, ms);
        tempTime += 24 * 60 * 60 * 1000;    // milliseconds in a day
        var tempDate = new Date(tempTime);
        year = tempDate.getUTCFullYear();
        month = tempDate.getUTCMonth();
        date = tempDate.getUTCDate();
    }

    var time = Date.UTC(year, month, date, hour, min, sec, ms);

    if (res[11] && res[11] != 'Z'){
        var ofs = 0;
        ofs += (parseInt(res[13],10) || 0) * 60*60*1000; // hours
        ofs += (parseInt(res[14],10) || 0) *    60*1000; // mins
        if (res[12] == '+') // if ahead subtract
            ofs *= -1;

        time += ofs
    }

    return new Date(time);
}
>