1

I'm writing a stored procedure for Cosmos DB. I am not very familiar with JavaScript.

I've been trying to get an ISO-8601 formatted Date, but have been unsuccessful so far. According to some docs I found, I should just be able to call toISOString on a Date. That does not work ("Object doesn't support property or method" error).

So I found this advice to define the prototype yourself:

function storedProcedure(arg) {
    if (!Date.prototype.toISOString) {
        // Here we rely on JSON serialization for dates because it matches
        // the ISO standard. However, we check if JSON serializer is present
        // on a page and define our own .toJSON method only if necessary
        if (!Date.prototype.toJSON) {
            var toISOString = function (date) {
                function f(n) {
                    // Format integers to have at least two digits.
                    return n < 10 ? '0' + n : n;
                }

                return date.getUTCFullYear() + '-' +
                    f(date.getUTCMonth() + 1) + '-' +
                    f(date.getUTCDate()) + 'T' +
                    f(date.getUTCHours()) + ':' +
                    f(date.getUTCMinutes()) + ':' +
                    f(date.getUTCSeconds()) + 'Z';
            };
        }

        Date.prototype.toISOString = Date.prototype.toJSON;
    }

    var now = Date.now();
    var iso8601 = now.toISOString();
    console.log("ISO " + iso8601);

    // other code
}

However, this still fails with:

Object doesn't support property or method 'toISOString'

I tried removing the prototype altogether and just using a function that takes a Date instead. However, then the same error occurred but for other members, like getUTCFullYear.

I tried also calling getSeconds and that failed for the same reason. Out of desperation, I tried listing out the object's properties using the getKeys function in this answer and it gives me an empty list.

What is going on here? How can I just get an ISO-8601 formatted Date representing the current time in UTC?

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393

1 Answers1

1

OK, it seems it was because I had used Date.now() per these docs instead of new Date() per this random google result.

I have no idea why this matters or how I could have known this (explanations welcome) but that was the underlying cause. I don't even need the prototype now.

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393