locked
Rest API always return the wrong value RRS feed

  • Question

  • My Tenant is in UTC +3 Time zone, however, when getting date field value, it's always 3 hours earlier than the real time.

    How to fix this, please share some suggestion.

    Thanks for help

    Wednesday, July 1, 2020 8:47 AM

Answers

  • Hi zhuw12,

    You can use Moment.js to covert UTC Time to Local Time in Rest API like this:

    <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 local time based on TimeZone
    			})
    			.fail(function(error){
    			    console.log(JSON.stringify(error));
    			}); 
                
            },
            error: function (data) {
                alert("Error");
                
            }
        });
        
        
            </script>

    Here is a similiar thread for your reference:

    How to convert SharePoint Date-Only field from UTC to local time zone

    Thanks

    Best Regards


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

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    • Marked as answer by zhw12 Friday, July 3, 2020 1:37 AM
    Thursday, July 2, 2020 2:08 AM