Function for calculating value that changes with date

My goal is to have NR update the cost per kWh based on the schedule that has been published by my utility provider. Currently they have published a pdf that shows the $/kWh for time periods through 2025. I would like to check the date (probably date.now) and determine what block it fits into and apply the appropriate rate. I'm not a JS programmer so this is not in my wheel house. I've found some code snippets but it appears I may be over complicating things.

var from = new Date("02/08/2017").getTime();
var to = new Date("05/08/2017").getTime();
var withinRange = today >= from && today <= to;

And here's the rate table:

effective date      $/kWh
1 Oct 2017          0.10414
1 Apr 2021          0.10118
1 Apr 2022          0.09822
1 Apr 2023          0.09527
1 Apr 2024          0.09231
1 Apr 2025          0.08935

I would typically use an if-elseif structure, but I'm not sure if there's a better way in JS.

So are the rate structures more complicated than what you have listed or is the list above the real list ?

(Wish i lived where you were and got those rates !!)

If the list above is it - then i do not know that i would overly complicate it - they are only going to change once per year on April 1st.

What are you wanting to achieve once you have this ?

Craig

Yeah, this is the actual rates. I just want to set the rate and then multiply by the kWh that I feed to it to determine the accumulated cost. I tried a basic approach but my JavaScript isn't that strong.

const now = Date.now();
var rate = -1;

if(now <= Date("1/4/2021")) {
   rate = 0.10414;
}
else if(now <= Date("1/4/2022")) {
   rate = 0.10118;
}
else if(now <= Date("1/4/2023")) {
   rate = 0.09822;
}
else if(now <= Date("1/4/2024")) {
   rate = 0.09527;
}
else if(now <= Date("1/4/2025")) {
   rate = 0.08935;
}


//msg.payload = msg.payload * rate;
msg.payload = rate;
return msg;

The function always returns -1 so I'm clearly not using either the date functions wrong.

Hi .. your research to use getTime() when comparing Dates is correct. you have to apply it to your code.
Also based on the MDN article on creating dates from strings, im not sure the slash (/) and the order of you string is valid.

const now = new Date().getTime();
node.warn(now)
var rate = -1;

if(now <= new Date("2021-4-1").getTime()) {
  rate = 0.10414;
}
else if(now <= new Date("2022-4-1").getTime()) {
  rate = 0.10118;
}
else if(now <= new Date("2023-4-1").getTime()) {
  rate = 0.09822;
}
else if(now <= new Date("2024-4-1").getTime()) {
  rate = 0.09527;
}
else if(now <= new Date("2025-4-1").getTime()) {
  rate = 0.08935;
}

//msg.payload = msg.payload * rate;
msg.payload = rate;
return msg;

:man_facepalming:
I didn't check the acceptable date format. Thanks for the updated code, it seems to work great!