Friday, April 8, 2016

Display Formatted Modified Date in Page Layout

I had a requirement to show the Modified Date of a page by Page layout.

I tried with the SharePointWebControls:FieldValue and SharePointWebControls:DateTimeField of Sharepoint control those controls doesn't support the Formatting of a date.

So i finally write a Rest API call to get the Modified Date of the Page and format it using Javascript .

Paste the below code before the closing of </asp:Content> tag in the Page Layout.


<div>Page Last Updated : <span id="spnModifiedDate"></span></div>


<script>
var monthNamesLower = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var relativePageURL = _spPageContextInfo.serverRequestPath;
var siteURL = _spPageContextInfo.webAbsoluteUrl;         
var query = siteURL + "/_api/web/getfilebyserverrelativeurl('/"+ relativePageURL +"')?    $select=TimeLastModified,ModifiedBy/Title,ModifiedBy/LoginName&$expand=ModifiedBy";
var call = $.ajax({
    url: query,
    type: "GET",
    dataType: "json",
    headers: {
        Accept: "application/json;odata=verbose"
    }       
});
call.done((function (data, textStatus, err){
 var date = new Date(data.d.TimeLastModified.replace("T", " ").replace("Z", "").replace(/-/g, "/"));
 var formatteddate = monthNamesLower[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
 $("#spnModifiedDate").text(formatteddate);

 }));
call.fail(function (err){

});
</script>

No comments:

Post a Comment