Convert Sage CRM date to a JavaScript date

Less than one minute read time.

Have you ever come across a date in CRM that you want to add a month or a day perhaps, but when you try doing that JavaScript gives you an error, perhaps Invalid Date, or the month gets read as a day and day as a month.
Certain regions use certain date formats that CRM makes available to them, through the user preferences section, however not all of these formats are convertible to JavaScript date standard, in fact most of them are, but not the ones that start with days. 

If the date starts with a month or a year, then it should convert fine, but starting with a day, will not convert correctly.

Here is a short JS function you can add to the custom js folder, as a global function, or prototype onto the date functions to convert the date to a JS date.

function convertToJSDate(cdate)
{
if(crm.CurrentUser.userpref_dateformat.startsWith("D") || crm.CurrentUser.userpref_dateformat.startsWith("d"))
  {
      if(cdate.indexOf(".") == 1)
        cdate = cdate.split('.')[2]+"-"+cdate.split('.')[1]+"-"+cdate.split('.')[0];
      else
        cdate = cdate.split('/')[2]+"-"+cdate.split('/')[1]+"-"+cdate.split('/')[0];
        
    return new Date(cdate);
  }
  else
  {
  	return new Date(cdate);
  }
}
  

usage ->

var d = $('#oppo_targetclose').val();
var dd = convertToJSDate(d);
//print the js date
//console.log(dd)

//add some months to the date
var addm = new Date(dd.setMonth(dd.getMonth()+8));
console.log(addm);