Function always return same value instead throw else clauseif condition is not valid
-
02-01-2021 - |
سؤال
I have this query running from JSLink into list. It get current time from moment.js
and compare date with sharepoint column ctx.CurrentItem.Cumplimiento;
and return result into column sCumplimientoInicial
function overrideCumplimiento(ctx) {
var sIconFileName = "";
var currentServerDateTime = moment().format("DD/MM/YYYY");
var sCumplimiento = ctx.CurrentItem.Cumplimiento;
var sCumplimientoInicial = ctx.CurrentItem.Fecha_x0020_Compromiso_x0020_Ini;
if(currentServerDateTime < sCumplimientoInicial){
sCumplimiento = 'Yes'
}else{
sCumplimiento = 'No'
}
return sCumplimiento;
}
Problem is when currentServerTime
is bigger than sCumplimientoInicial
it return "Yes" instead "No", and it always return Yes. Any idea what is wrong there?
I think it is because sCumplimiento
is an string and no date. Because if I select first, second of any month it return no
so it is not comparing from dates just from string. How can I achieve this comparation of dates correctly?
UPDATE: As comments below I try to do it using
var sCumplimientoInicial = moment("ctx.CurrentItem.Fecha_x0020_Compromiso_x0020_Ini");
But I getting "Invalid Date"
المحلول
To cast a string
field to date
try this
var FDate = new Date(your field with DateTime Data Type);
Ex: var FDate = new Date(ctx.CurrentItem.Fecha_x0020_Compromiso_x0020_Ini);
Note: in case your field is string, try to parse your code with moment
var momentDate = moment("your field");
In case it's not working, try to customize your string in the correct date format "MM/dd/yyyy"
then parse the output to date as the following
var day = str.substring(0,2);
var mon = str.substring(3,5);
var yr = str.substring(6,10);
var dateformated = mon + "/" + day + "/" + yr;
var sCumplimientoInicial = Date.parse(dateformated);
To compare with today
try this
var today = new Date();
So the condition should look like
if(today < FDate )
{
sCumplimiento = 'Yes'
}
else
{
sCumplimiento = 'No'
}
نصائح أخرى
You do not have to do the calculations;
SharePoints adds a 'GetDaysAfterToday' function