Javascript Sharepoint Compare Data Field with Date Today

Asked

Viewed 107 times

0

I have a list at Sharepoint with the code below: I need to compare the date of the field "Data_x0020_de_x0020_delivery" with the current date "today", but by the code below is comparing only the first digit of the date, for example, if today is 03/03/2017 and the field "Data_x0020_de_x0020_delivery" is on 20/02/2017 is comparing only the first digits in the case, '03' with '20'

How do I compare the two dates?

(function () {
  var fieldCtx = {};


  fieldCtx.Templates = {};
  fieldCtx.Templates.Fields = {
    "Progress": {
        "View": ProgressFieldViewTemplate
    }
  };

  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(fieldCtx);
})();

function ProgressFieldViewTemplate(ctx) {

  var _statusValue = ctx.CurrentItem.Data_x0020_de_x0020_Entrega;
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1; //January is 0!
  var yyyy = today.getFullYear();

  if(dd<10) {
    dd='0'+dd
  } 

  if(mm<10) {
    mm='0'+mm
  } 

  today = dd+'/'+mm+'/'+yyyy;

  if (_statusValue > today)
  {
    return "<img src='https://xxxxxxxxxxxx/sites/intralogo/SiteAssets/icons/Green.png'/>";
  }
  else if (_statusValue == today)
  {
    return "<img src='https://xxxxxxxxxx/sites/intralogo/SiteAssets/icons/Yellow.png'/>";
  } 
  else if (_statusValue < today)
  {
    return "<img src='https://xxxxxxxxx/sites/intralogo/SiteAssets/icons/Red.png'/>";
  }   
}
  • Voce comparing two strings, Voce should compare two objects Date

1 answer

0

I believe this will help you, you must take your date, turn it into an object Date javscript and then yes compare.

As you want to disregard the hours, it was necessary to create a Date variable from the value of the current date to be able to make the correct comparison.

follows code below:

function ProgressFieldViewTemplate(ctx) {
  var dateStr = ctx.CurrentItem.Data_x0020_de_x0020_Entrega;

  var dt = new Date(parseInt(dateStr.substr(6,4)) 
                  , parseInt(dateStr.substr(3,2)) -1 
                  , parseInt(dateStr.substr(0,2)));
  var today = new Date();

  today = new Date(today.getFullYear(), today.getMonth(), today.getDate());

  if(dt < today){
    return "<img src='https://xxxxxxxxx/sites/intralogo/SiteAssets/icons/Red.png'/>";
  } else if ( dt > today ){
    return "<img src='https://xxxxxxxxxxxx/sites/intralogo/SiteAssets/icons/Green.png'/>";
  }else {
    return "<img src='https://xxxxxxxxxx/sites/intralogo/SiteAssets/icons/Yellow.png'/>";
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.