日期代码之间的比较

Comparison between date codes

我有一组这样的值:

var array_1 = ["1W", "2W", "3W","1M", "2M", "3M", "6M","9M","1Y"]

W 代表周,M 代表月,Y 代表年。我如何进行字符串比较,以便在

之间进行比较

"1Y" > "9M"

将 return 是

您可以采用相同的基础,例如每项信息的天数,并采用相当于天数的字母和 return 产品。

function getDays(string) {
    return string.slice(0, -1) * { W: 7, M: 30, Y: 365 }[string.slice(-1)];
}

var array = ["1W", "2W", "3W","1M", "2M", "3M", "6M","9M","1Y"]

console.log(array.map(getDays));

这是一个易于扩展的简单解码器。

本质上它过滤数值,然后 returns 它根据它在字符串 (W, M, ...) 中找到的时间符号乘以某个常数。

function decodeDateCode(dateCode) {
  var numeric = parseInt(dateCode.replace(/\D/igm, ''), 10);
  if (dateCode.indexOf("D") >= 0) {
    return numeric;
  }
  if (dateCode.indexOf("W") >= 0) {
    return numeric * 7;
  }
  if (dateCode.indexOf("M") >= 0) {
    return numeric * (365 / 12);
  }
  if (dateCode.indexOf("Y") >= 0) {
    return numeric * 365;
  }
}
//test
var dateCodes = ["1W", "2W", "3W", "1M", "2M", "3M", "6M", "9M", "1Y", "50W"];
//Decode entire list
console.log("Decoded list:", dateCodes.map(decodeDateCode));
//Sort entire list in descending order
console.log("Sorted descending list:", dateCodes.sort(function(a, b) {
  return decodeDateCode(b) - decodeDateCode(a);
}));
//Make simple comparison
console.log("Simple comparison:", decodeDateCode("1Y") > decodeDateCode("9M"));