0

I am using below code to retrieve data from my list:

$http({
        method: 'GET',
        url: _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('Mylist')/items?$select=*,Resource/ID&$expand=Resource&$filter=(Resource/ID eq "+ resId +")&$orderby=EndDate desc",
        headers: {
            'Accept': 'application/json; odata=verbose'
        }
    }).success(function (d) {

        dataM = [];
        $(d.d.results).each(function (i, e) {

                dataM.push({
                id: e['Id'],
StartDate: svc.formatDate(new Date(e['StartDate'])),
EndDate: svc.formatDate(new Date(e['EndDate'])),
                ResourceDailyRate: e['Resource_x0020_Daily_x0020_Rate'],
                ClientDailyRate: e['Client_x0020_Daily_x0020_Rate'],
                PoliceCheck : ((e['Police_x0020_Check'] == null || e['Police_x0020_Check'] == 'Select')? 'X' : e['Police_x0020_Check']),
                CreatedClientContract: (e['Created_x0020__x0028_Client_x002'] == null ? 'X' : e['Created_x0020__x0028_Client_x002']),
                SignedApproved: (e['Signed_x002f_Approved_x0020__x00'] == null ? 'X' : e['Signed_x002f_Approved_x0020__x00']),
                CounterSigned: (e['Countersigned_x0020__x0028_Clien'] == null ? 'X' : e['Countersigned_x0020__x0028_Clien']),
                SignedResource : (e['Signed_x0020__x0028_Resource_x00'] == null ? 'X' : e['Signed_x0020__x0028_Resource_x00']),
                CounterSignedResource : (e['Countersigned_x0020__x0028_Resou'] == null ? 'X' : e['Countersigned_x0020__x0028_Resou']),
                PORecieved : (e['PO_x0020_Recieved'] == null ? 'X' : e['PO_x0020_Recieved']),
                ReoccurringInvoice : (e['Reoccurring_x0020_Invoice'] == null ? 'X' : e['Reoccurring_x0020_Invoice']),
                DocType: e['Doc_x0020_Type'],
                DocID: e['Doc_x0020_ID'],
                PONumber :e['PO_x0020_Number']

            });    
    });
        console.log('dataM',dataM);
        callback(dataM);
        deferred.resolve(dataM);
    }).error(function (er) {
        alert(er);
    });            
}

It works as expected except it is giving me 1 day earlier date in start & end date. Can anyone suggest some work around?

In svc.formatDate function I tried below code:

svc.formatDate = function (dt) {
            var options = {
                day: "numeric", month: "long", year: "numeric"
            };
        return dt.toLocaleDateString('en-AU', options);
    }

Also I have checked JSON.stringify & JSON.parse in other stack overflow blogs. but its not helping.

1

Go Step by step. first retrieve all records and print in console check all data is return. if all data is return by server then only mistake is date object which we use in javascript.

clearly javascript is client side. so it is taken a client environment date. if you need to find server time then you have to find a server time zone url

function getSPCurrentTime(webUrl) { return $.ajax({ url: webUrl + "/_api/web/RegionalSettings/TimeZone", method: "GET", headers: { "Accept": "application/json; odata=verbose" } }).then(function(data){ var offset = data.d.Information.Bias / 60.0; return new Date( new Date().getTime() - offset * 3600 * 1000); }); }

Usage:

getSPCurrentTime(_spPageContextInfo.webAbsoluteUrl) .done(function(value) { console.log(value.toUTCString()); // get current SP server time in UTC }) .fail( function(error){ console.log(JSON.stringify(error)); });

please verify with your data. please let me know in case of any problem.

1

It's a common issue when retrieving the date object in SharePoint because REST do not bring back the client side time, it brings back the server time. The solution is to either reset the time (see article below), or add UTC+ in front of it if you have users cross different time zones. So the time is dynamic based on their locale.

This blog has further information:

http://julieturner.net/2017/11/sharepoint-rest-datetime-updates/

  • I have gone deep in it and the issue is I am getting the wrong date input from rest itself. So putting UTC in front of it do not fix the issue. In SharePoint If I edit or view item properties, I am able to see correct date. So I am not able to change time. – love thakker Dec 14 '17 at 12:17
  • I'm not sure if I understand the "getting the wrong date input from rest" you mean output? The date/time you retrieve is wrong compare to the timestamp in the item. – YogaPanda Dec 14 '17 at 14:23
  • yes. I have checked rest by typing that url in browser. It returns date 1 day less. – love thakker Dec 15 '17 at 9:00
1

I recently had to solve this.

First, know that Sharepoint returns the original date entered through Sharepoint, minus the Site Setting's Regional timezone offset. For example, my site is set at +10 Melbourne, Australia time (Site Actions > Site Settings > Site Administration > Regional Settings > Timezone). A 10AM date at +1000 (AEST), would be stored as, for example, 2020-09-15T00:00:00Z (UTC).

It looks like Negi Rox's answer programmatically returns this value for you (url: webUrl + "/_api/web/RegionalSettings/TimeZone")

To use this, we need to convert to milliseconds because JavaScript internally works that way. +10hrs = 10*60*60*1000 milliseconds.

We also need to be aware that "new Date()" utilises the local timezone, and this local offset must be removed. We can work out the local offset by getTimezoneOffset(), which returns the time in minutes (in negative, so multiply by -1)

Put it all together, and we get the following:

var tempMeetingDate = new Date(Date.UTC(tempMeetingYear,tempMeetingMonth,tempMeetingDay,tempMeetingHour,tempMeetingMinute,0)); //regex to extract year, month etc. not shown
var userOffset = tempMeetingDate.getTimezoneOffset()*60*1000*-1;
var serverOffset = 10*60*60*1000;
var offsettempMeetingDate = new Date(tempMeetingDate.getTime() - userOffset + serverOffset); //should return the right day/time regardless of local time

This does not take into consideration daylight saving. But that would be another whole question & answer (& many more lines of code! Or library such as Moment Timezone).

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.