How to get current user time on client side (JavaScript)

Recently I got requirement to fill-in field on a web resource with current user time (CRM settings should be took into account).

I use following code to implement requirement:
1. Retrieve user settings 2. Ask server to execute UtcTimeToLocalTime request with user time zone provided

This is code:
DateTimeHelper = {};

(function (DateTimeHelper, jQuery, $) {

    DateTimeHelper.GetUserLocalTime = function (date) {
        var userId = context().getUserId();
        var settings = getCurrentUserSettings(userId);
        var timeZoneCode = settings.TimeZoneCode;
        var dateTime = Teoco.DateTimeHelper.UtcTimeToLocalTime(timeZoneCode, date);
        return dateTime;
    };

    DateTimeHelper.UtcTimeToLocalTime = function (timeZoneCode, dateTime) {
        var req = getXhr();
        req.open("POST", getServicePath(), false);
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");

        var xml =
            "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
            "  <s:Body>" +
            "    <Execute xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
            "      <request i:type='b:LocalTimeFromUtcTimeRequest' xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts' xmlns:b='http://schemas.microsoft.com/crm/2011/Contracts'>" +
            "        <a:Parameters xmlns:c='http://schemas.datacontract.org/2004/07/System.Collections.Generic'>" +
            "          <a:KeyValuePairOfstringanyType>" +
            "            <c:key>TimeZoneCode</c:key>" +
            "            <c:value i:type='d:int' xmlns:d='http://www.w3.org/2001/XMLSchema'>" + timeZoneCode + "</c:value>" +
            "          </a:KeyValuePairOfstringanyType>" +
            "          <a:KeyValuePairOfstringanyType>" +
            "            <c:key>UtcTime</c:key>" +
            "            <c:value i:type='d:dateTime' xmlns:d='http://www.w3.org/2001/XMLSchema'>" + dateTime.toISOString() + "</c:value>" +
            "          </a:KeyValuePairOfstringanyType>" +
            "        </a:Parameters>" +
            "        <a:RequestId i:nil='true' />" +
            "        <a:RequestName>LocalTimeFromUtcTime</a:RequestName>" +
            "      </request>" +
            "    </Execute>" +
            "  </s:Body>" +
            "</s:Envelope>";

        req.send(xml);

        var date = null;

        if (req.status === 200) {
            var resultXml = req.responseXML;
            var dateString = $(resultXml).find("value").text()
            date = new Date(dateString);
        }
        else {
            alert("Failed to retrieve current user local time");
            throw "Failed to retrieve current user local time";
        }

        return date;
    };

    function getCurrentUserSettings(userId) {
        var request = "/UserSettingsSet?$filter=SystemUserId eq guid'" + userId + "'";

        var settings = null;

        callOData(request,
            function (data) {
                if(data != null && data.results != null && data.results.length != 0)
                {
                    settings = data.results[0];
                }
            },
            function (xhr) {
            });

        if (settings == null) {
            alert("Failed to load current user settings");
            throw "Failed to load current user settings";
        }

        return settings;
    }

    function callOData(request, onSuccess, onError) {
        var req = getXhr();
        req.open("GET", getODataPath() + request, false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");

        req.send();

        if (req.status === 200) {
            onSuccess(JSON.parse(req.responseText).d);
        }
        else {
            onError(req);
        }
    }

    function getServicePath() {
        return getClientUrl() + "/XRMServices/2011/Organization.svc/web";
    }

    function getODataPath() {
        return getClientUrl() + "/XRMServices/2011/OrganizationData.svc/";
    }

    function getClientUrl() {
        var serverUrl = typeof context().getClientUrl !== "undefined" ? context().getClientUrl() : context().getServerUrl();
        if (serverUrl.match(/\/$/)) {
            serverUrl = serverUrl.substring(0, serverUrl.length - 1);
        }
        return serverUrl;
    }

    function context() {
        var oContext;
        if (typeof window.GetGlobalContext != "undefined") {
            oContext = window.GetGlobalContext();
        }
        else {
            if (typeof Xrm != "undefined") {
                oContext = Xrm.Page.context;
            }
            else if (typeof window.parent.Xrm != "undefined") {
                oContext = window.parent.Xrm.Page.context;
            }
            else {
                throw new Error("Context is not available.");
            }
        }
        return oContext;
    }

    function getXhr() {
        if (XMLHttpRequest) {
            return new XMLHttpRequest();
        }
        try {
            return new ActiveXObject('MSXML2.XMLHTTP.6.0');
        } catch (e) {
            try {
                return new ActiveXObject('MSXML2.XMLHTTP.3.0');
            } catch (e) {
                alert('This browser is not AJAX enabled.');
                return null;
            }
        }
    }

})(DateTimeHelper, jQuery, jQuery);
And this is usage example:
var today = Teoco.DateTimeHelper.GetUserLocalTime(new Date());

2 comments

avatar

I am regular reader of your blog and no doubt it all stuff is awesome. The best thing about your sharing and posting is that you always provide content that is helpful for both the newbie and experts.CRM Software Development

avatar

Good Post. Avail Microsoft Dynamics Web Development Service that transform your business with customized business solutions.