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:
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
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("Content-Type", "text/xml; charset=utf-8");
 
        var xml =
            "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
            "  <s:Body>" +
            "      <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:
10
var today = Teoco.DateTimeHelper.GetUserLocalTime(new Date());
Pages (3)123 Next