none
Date is returning one day less when using REST Api

    질문

  • hi,

    i have 2 date columns in the Custom list and i am trying to get the values using Jquery & Rest Api

    it is returning the date one day less

    How can i get the proper date or how to convert this date value



    sal

    2018년 5월 17일 목요일 오전 11:23

답변

  • Hi Ali,

    In Rest Response, DateTime value is stored as UTC Date, but from UI, it will converted based on Site Region Time Zone Settings, here is a code snippet which helps to covert UTC Date to Local Server Date based on Time Zone:

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
    	<script type="text/javascript">
    			var TimeZoneUtilities = {
    			  utcToLocalTime: function getSPCurrentTime(webUrl,value) {
    			    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 + data.d.Information.StandardBias + data.d.Information.DaylightBias) / 60.0;
    			      return moment.utc(value).utcOffset(offset);
    			    });
    			  }
    			};	  
    	$.ajax({
            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('RestDate')/items(1)",
            type: "GET",
            contentType: "application/json;odata=verbose",
            headers: {
                "Accept": "application/json;odata=verbose"
             },
            success: function (data) {
                console.log("UTC Time: "+ data.d.testdate);//UTC datetime value from REST response
                var testDateString = data.d.testdate; 
    			var orderDate = new Date(testDateString);
    			TimeZoneUtilities.utcToLocalTime(_spPageContextInfo.webAbsoluteUrl,orderDate)
    			.done(function(value)
    			{
    			    console.log("Server time: " + value._d.toISOString());//Convert to Server UI time based on TimeZone
    			})
    			.fail(function(error){
    			    console.log(JSON.stringify(error));
    			}); 
                
            },
            error: function (data) {
                alert("Error");
                
            }
        });
        
        
            </script>
    

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnsf@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    • 답변으로 표시됨 SB Ali 2018년 5월 21일 월요일 오전 7:04
    2018년 5월 18일 금요일 오전 8:19
  • Hi,

    Thanks for sharing, i also tried using other option as i want to convert the date format, below is the sample script for that. 

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
     $(function () {
     
     
     var requestUri = _spPageContextInfo.webAbsoluteUrl +
    "/_api/Web/Lists/getByTitle('testlist')/items(1)";
    					  
    		 $.ajax({
    			 url: requestUri,
    			 type: "GET",
    			 headers: { "ACCEPT": "application/json;odata=verbose" },
    			 success: function (data) {
    			 if(data.d.results.length>0){
    				
    				 var field=data.d.results[0];
    				 var duedate = field.DueDate;
    				 var duedate1;
    
                     duedate1 = convertUTCDateToLocalDate(new Date(duedate));											 
                     console.log(formatDate(duedate1));
    				 
    				 }
    	
    		     },
    				
    		 error: function () 
    		 {
    			 //alert("Failed to get details");
    		 }
    
    	 });
    	 
    	 
     });	 
    	 
    	 
    	 //Converting UTCDate
    	 function convertUTCDateToLocalDate(date) 
    	{
             var newDate = new Date(date);
             newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset());
             return newDate;
        }
    
    
         //Format Date
         function formatDate(d)
        {
             date = new Date(d)
             var dd = date.getDate(); 
             var mm = date.getMonth()+1;
             var yyyy = date.getFullYear(); 
             if(dd<10){dd='0'+dd} 
             if(mm<10){mm='0'+mm};
             return d = dd+'/'+mm+'/'+yyyy
        }
    	
    </script>


    sal

    • 답변으로 표시됨 SB Ali 2018년 5월 21일 월요일 오전 7:04
    2018년 5월 20일 일요일 오전 9:53

모든 응답

  • Hi Ali,

    In Rest Response, DateTime value is stored as UTC Date, but from UI, it will converted based on Site Region Time Zone Settings, here is a code snippet which helps to covert UTC Date to Local Server Date based on Time Zone:

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
    	<script type="text/javascript">
    			var TimeZoneUtilities = {
    			  utcToLocalTime: function getSPCurrentTime(webUrl,value) {
    			    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 + data.d.Information.StandardBias + data.d.Information.DaylightBias) / 60.0;
    			      return moment.utc(value).utcOffset(offset);
    			    });
    			  }
    			};	  
    	$.ajax({
            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('RestDate')/items(1)",
            type: "GET",
            contentType: "application/json;odata=verbose",
            headers: {
                "Accept": "application/json;odata=verbose"
             },
            success: function (data) {
                console.log("UTC Time: "+ data.d.testdate);//UTC datetime value from REST response
                var testDateString = data.d.testdate; 
    			var orderDate = new Date(testDateString);
    			TimeZoneUtilities.utcToLocalTime(_spPageContextInfo.webAbsoluteUrl,orderDate)
    			.done(function(value)
    			{
    			    console.log("Server time: " + value._d.toISOString());//Convert to Server UI time based on TimeZone
    			})
    			.fail(function(error){
    			    console.log(JSON.stringify(error));
    			}); 
                
            },
            error: function (data) {
                alert("Error");
                
            }
        });
        
        
            </script>
    

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnsf@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    • 답변으로 표시됨 SB Ali 2018년 5월 21일 월요일 오전 7:04
    2018년 5월 18일 금요일 오전 8:19
  • Hi,

    Thanks for sharing, i also tried using other option as i want to convert the date format, below is the sample script for that. 

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
     $(function () {
     
     
     var requestUri = _spPageContextInfo.webAbsoluteUrl +
    "/_api/Web/Lists/getByTitle('testlist')/items(1)";
    					  
    		 $.ajax({
    			 url: requestUri,
    			 type: "GET",
    			 headers: { "ACCEPT": "application/json;odata=verbose" },
    			 success: function (data) {
    			 if(data.d.results.length>0){
    				
    				 var field=data.d.results[0];
    				 var duedate = field.DueDate;
    				 var duedate1;
    
                     duedate1 = convertUTCDateToLocalDate(new Date(duedate));											 
                     console.log(formatDate(duedate1));
    				 
    				 }
    	
    		     },
    				
    		 error: function () 
    		 {
    			 //alert("Failed to get details");
    		 }
    
    	 });
    	 
    	 
     });	 
    	 
    	 
    	 //Converting UTCDate
    	 function convertUTCDateToLocalDate(date) 
    	{
             var newDate = new Date(date);
             newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset());
             return newDate;
        }
    
    
         //Format Date
         function formatDate(d)
        {
             date = new Date(d)
             var dd = date.getDate(); 
             var mm = date.getMonth()+1;
             var yyyy = date.getFullYear(); 
             if(dd<10){dd='0'+dd} 
             if(mm<10){mm='0'+mm};
             return d = dd+'/'+mm+'/'+yyyy
        }
    	
    </script>


    sal

    • 답변으로 표시됨 SB Ali 2018년 5월 21일 월요일 오전 7:04
    2018년 5월 20일 일요일 오전 9:53
  • Hi Ali,

    Thanks for sharing the solution, you could Mark both replies as answer if they are helpful so that it could help others who stuck with the same issue in the forum.

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnsf@microsoft.com.


    Click here to learn more. Visit the dedicated forum to share, explore and talk to experts about Microsoft Teams.

    2018년 5월 21일 월요일 오전 5:39