0

There is a table with data and dates. Please help me to make a correct condition so that when it is triggered, the date will be coloured in different colours. The table has a Deadline column. I need the date to be colored red 5 days before the deadline, and gray after the date has passed. In other cases it is black. All in all I'm not really getting it right. The date in the column is written in this order 2023-02-01

moment(currentRow["Deadline"]).fromNow() >= "in 5 days"?'#f50202' : moment(currentRow["Deadline"]).fromNow() > "in 0 days"?
'#0d0d0d' : '#999999'

Tried working with a simple condition if the deadline date is less than the current text is greyed out. I can't find a solution to the more complex condition yet.

IndieDev
  • 1
  • 1

1 Answers1

1

moment's fromNow method returns a string, so you are comparing strings, not relative times.

The >= operator will compare the strings character by character until it reaches different characters, then returns the result of that comparison. So "2 hours ago" >= "1 year ago" will return true when you might expect it to return false. Similarly "in 5 minutes" >= "in 4 years" will also return true.

What you need is something like:

moment(currentRow["Deadline"]) >= moment().add(5, 'days')

or, if you want to just compare the date and ignore time:

moment(currentRow["Deadline"]) >= moment().add(5, 'days').startOf('day')

Note that if currentRow["Deadline"] does not resolve to a format understood by moment.js, you should also include the format so that it is parsed correctly, otherwise it will fall back to implementation dependent heuristics for parsing.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Thank you very much for your reply. Your first option works. There is another problem though, I need the deadline date, which is later than today, to be greyed out. It is still coloured red. Can you tell me how to do it? Conditionally there is a date 2023-01-05 it should be colored in gray because it is later than today. And date 2023-02-08 continues to be red until 2023-02-08 is on the calendar. – IndieDev Feb 06 '23 at 19:10
  • You just use similar code for other parts of the condition, so something like `moment(currentRow["Deadline"]) >= moment().add(5, 'days')? : moment(currentRow["Deadline"]) >= moment().startOf('day')? : `. So if the date is 5 or more days in the future, it's green. If it's 0 to 4 days in the future, it's red. Otherwise, it must be in the past so it's grey. – RobG Feb 07 '23 at 03:35