[FFC学习笔记]friendly-date-ranges

friendly-date-ranges

注意事项

  • 变量拼写
  • 字符串转数字
  • if语句用{},避免误写分号
  • 理解条件

var monthCoin = {
  "01":"January",
  "02":"February",
  "03":"March",
  "04":"April",
  "05":"May",
  "06":"June",
  "07":"July",
  "08":"August",
  "09":"September",
  "10":"October",
  "11":"November",
  "12":"December"
};

function lessThanOneYear(start, end){
  var year =  end[0] - start[0];
  if(year === 0)
    return true;
  if(year > 1)
    return false;
  // 差一年的要看月份
  var month = end[1].replace(/^0/,"") - start[1].replace(/^0/,"");
  console.log(month);
  if(month < 0){
    return true;
  }
  if(month > 0){
    return false;
  }
  // 同月的看日期

  var day = end[2].replace(/^0/,"") - start[2].replace(/^0/,"");
  console.log(day);
  if(day < 0)
    return true;
  else
    return false;

}
function displayMonth(arr){
  return monthCoin[arr[1]];
}
function displayDay(arr){
  if(arr[2]==="01")
    return "1st";
  else if( arr[2] === "02")
    return "2nd";
  else if(arr[2] === "03")
    return "3rd";
  else 
    return arr[2].replace(/^0/,"") + "th";
}
function displayYear(arr){
  return arr[0];
}
function makeFriendlyDates(arr) {
  var startArr = arr[0].split("-");
  var endArr = arr[1].split("-");
  var result = [];
  var startResult = "";
  var endResult = "";
  startResult = displayMonth(startArr);
  startResult = startResult +  " " + displayDay(startArr);
  if(startArr[0] === "2016" && lessThanOneYear(startArr,endArr)){
    //今年且小于一年,不显示 条件一 
  }else{
     startResult = startResult + ", " + displayYear(startArr);
  }
  result.push(startResult);

  if(arr[1] !== arr[0]){ //开始结束是同一天,就不用打印后面的了

    if(lessThanOneYear(startArr,endArr)){ //是否小于一年,条件二
      if(startArr[1] === endArr[1] && startArr[0] === endArr[0] ){ //是否同年月,条件三

        endResult += displayDay(endArr);
      }else{
        endResult += displayMonth(endArr);
        endResult += " ";
        endResult += displayDay(endArr);
      }
    }else{ 
        endResult += displayMonth(endArr);
        endResult += " ";
        endResult += displayDay(endArr); 
        endResult += ", ";
        endResult += displayYear(endArr);
    }
    result.push(endResult);
  }
  return result;
}

makeFriendlyDates(["2022-09-05", "2023-09-04"]);

你可能感兴趣的:([FFC学习笔记]friendly-date-ranges)