Sharepoint dates and Javascript

If you’ve ever worked with JS and Sharepoint date fields you will know the problem, if you haven’t I’l try and save you some time.

Javascript typically see’s how Sharepoint stores its dates as invalid, and reformatting the date in JS to some usable format tends to require too many lines of code and various issues.

I use moment.js to do this, makes the process much simpler. eg.

<script src="https://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script src="http://xyz.com/moment.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">

// Get todays date using moment.js
var today = moment()


function PreSaveAction() {

//Get the date value from the Sharepoint form using Jquery
SharepointDate = $("input[title='Date to be reviewed']").val();

// Convert Sharepoint date field to a JS date
var SPDatejs = (SharepointDate);

// Format the JS date using moment.JS so we can do the comparison
var SPdatejs2 = moment(SPDatejs, "DD-MM-YYYY");

//Check the dates to see if the values are valid to submit

    if (SPdatejs2 < today && SPdatejs2 !=""){
        alert("The value 'Date to be reviewed' must be in the future");
        return false;
    }   
        return true;
}
 </script>

Uncategorized

%d bloggers like this: