ArcGIS Server and Javascript Dates

If you run into dates being a day early in ArcGIS javascript or other apps, here’s what’s happening I think ; )

FYI, UTC is for all practical purposes the same as GMT.

Esri recommends that databases are in UTC time. And if I’ve got this right, unless you set a time zone in your layer, you are entering a date in a date field as UTC. Mostly this is fine.You understand that the date refers to Pacific time for instance. You understand the date comes back to you the same value you put into the field. The problem comes when the browser or iOS or whatever device automatically localizes on initialization.

Problem: When ArcGIS Server returns a date, it sends milliseconds since epoch UTC (unix time). However, the Javascript Date object always creates a localized date when you use that to instantiate a Date object, e.g. Pacific Daylight Time, moving it back -7 hours. Thus, March 16 0:00am in the data becomes March 15 5:00pm — one day early.

A Solution: Keep everything in UTC. Use the javascript getUTC functions to return UTC time, which will match the stored date. (Yes, you could break this out into templates and formats, but really, how many different formats do you need for most apps.)


function getUTCDateYYYYMMDD(milliSecUnix) {
    var d, mm, dd;
    if (milliSecUnix) {
        d = new Date(milliSecUnix);
        mm = d.getUTCMonth() + 1;
        dd = d.getUTCDate();
        return (d.getUTCFullYear() + "-" +
                ((mm < 10) ? "0" + mm : mm) + "-" +
                ((dd < 10) ? "0" + dd : dd));
    }
    else {
        return "";
    }
}

2 comments

  1. Dfriedrich says:

    “Esri recommends that databases are in UTC time”
    Can you point me to anything Esri has published that addresses this?

    • drhall001 says:

      Hey David, long time no chat — hope you’re doing well. May have gotten it from here –

      http://resources.arcgis.com/en/help/main/10.1/index.html#//01m600000068000000

      “When you enable editor tracking on a dataset, you can record the dates of the edits in either UTC or the database’s time zone.

      If you’ll be copying or replicating data across time zones, or if you’re planning on editing through a feature service, use UTC, a standard that is unaffected by differences in time zones. Since editors can apply edits from potentially anywhere in the world, UTC works well.

      Recording in the database’s time zone is recommended only if you are certain all edits will be performed within the same time zone.”

Leave a Reply

Your email address will not be published. Required fields are marked *