LoginSignup
1
1

More than 5 years have passed since last update.

MongoDBのISODateの関数仕様を見る

Last updated at Posted at 2014-10-02

Mongo Shell 内で ISODate.toString() すれば実装が見れます。
以下は、MongoDB-2.6.4 での出力例です。

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

Date に比べて初期化時に渡せる引数のパターンが少なかった。
タイムスタンプはダメなんすね..

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1