简体   繁体   中英

Comparing two strings in Google Apps Script

I am using the following part of a script to try to pick up the currency exchange rate for several currencies against EUR on the date that the dividend is actually paid. This is to make sure I don't need to remember to calculate the value in EUR which I then use to calculate the performance of my portfolio in Google Spreadsheets

Basically there is a cell where the current date is (variable "tamapaiva") and the date when the specific dividend is paid (variable "osingonmaksupaiva"). In the script, I am comparing those two dates but for some reason, they never match even though the debug view shows that they are exactly the same.

The reason is probably a very simple one but I'd appreciate if you could take a look.

  // Calculate the value of dividends in EUR
  var i = 3;
  var tamapaiva = osinkoSheet.getRange(1, 9).getValue();
  var osingonmaksupaiva = "";
  var osingonmaksupaiva = osinkoSheet.getRange(i,1).getValue();

  while(osingonmaksupaiva != ""){
    var valuutta = osinkoSheet.getRange(i,5).getValue();
    if(valuutta == "GBP" && tamapaiva == osingonmaksupaiva){
      var kurssi = portfolioSheet.getRange(2, 16).getValue();
      osinkoSheet.getRange(i, 6).setValue(kurssi);
    }
    else if(valuutta == "USD" && tamapaiva == osingonmaksupaiva){
      var kurssi = portfolioSheet.getRange(2, 15).getValue();
      osinkoSheet.getRange(i, 6).setValue(kurssi);
    }
    else if(valuutta == "DKK" && tamapaiva == osingonmaksupaiva){
      var kurssi = portfolioSheet.getRange(2, 17).getValue();
      osinkoSheet.getRange(i, 6).setValue(kurssi);
    }
      i++;
      osingonmaksupaiva = osinkoSheet.getRange(i,1).getValue();
  }

On top of answers Compare two dates with JavaScript

just convert input into Date object and convert to common format, because w/o it you can't use == or === comparison. You can convert it into miliseconds with .getDate() and compare like below:

Example:

var tamapaiva = osinkoSheet.getRange(1, 9).getValue();
var osingonmaksupaiva = osinkoSheet.getRange(i,1).getValue();

should be changed into

var tamapaiva = new Date(osinkoSheet.getRange(1, 9).getValue()).getTime();
var osingonmaksupaiva = new Date(osinkoSheet.getRange(i,1).getValue()).getTime();

Above will convert both values into Number, which now can be easily compared. Thus

tamapaiva == osingonmaksupaiva

will produce now the desired result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM