4

My client machine and server machine has time offset of 2:30 hours. So when I try to retrieve Date/Time field using JSOM, it gives time according to offset.

oListItem.get_item("Modified");

So how to get server time even when creating new Date() object. Can it be acheived by new SP.ClientContext.get_current().get_web().get_regionalSettings()

6

Yes you should get the site's TimeZone first and then convert your DateTime accordingly.

function getTimeZoneAndServerDateTime() {

    var context = SP.ClientContext.get_current();
    var web = context.get_web();
    var timeZone = web.get_regionalSettings().get_timeZone();
    context.load(timeZone);
    context.executeQueryAsync(
    function onSucceeded() {
        var info = timeZone.get_information();
        var offset = (info.get_bias() + info.get_daylightBias()) / 60.0;
        var serverDateTimeNow = new Date(new Date().getTime() - offset * 3600 * 1000).toISOString();
        console.log("serverDateTimeNow: " + serverDateTimeNow);
    },
     Failure
    );

}

function Failure() {
    alert("error");
}

Also Vadim Gremyachev has posted nice answer here at sharepoint designer - get current server datetime through javascript REST

  • 1
    Thanks. That works fine for retrieving Server Date. But how to save the date/time in server date/time format ? – Yayati Jul 17 '15 at 9:31
  • Where do you want to save date values? In some list column? Also keep in mind that sharepoint stores date in utc format. – Asad Refai Jul 17 '15 at 9:45
  • Yes.There is an editable Date/Time Column which I have to set with user editable date. – Yayati Jul 17 '15 at 10:06
  • This answer is wrong. If the site is in a time zone that has DST, it will only produce the correct result during the DST part of the year. – JLRishe Nov 10 '17 at 5:13
  • @JLRishe Is that because the daylightBias will always return a value even if DST is not active? – Dinerdo Apr 13 '18 at 22:23
0

I tried the accepted answer but it seems to give wrong time. I found this post which explains a better way and it seems to work for me always.

You use _spPageContextInfo.clientServerTimeDelta to get the time delta and then add that to current date time.

var currentServerDateTime = new Date(new Date().getTime() + _spPageContextInfo.clientServerTimeDelta);
-1

Try this one

var sysDateTime = new Date("<%= System.DateTime.Now %>");

You need to connect your site through COM and then perform this one. May be this can help you

  • He needs a JavaScript/ECMA solution. I don't think your solution wil work that way.:) – Taran Goel Jul 10 '15 at 13:40
  • It should work in Javascript also..!! – Kaushal Khamar Jul 11 '15 at 5:34
  • The <%= System.DateTime.Now %> isn't JavaScript. – JLRishe Nov 10 '17 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.