Search code examples
vue.jsvue-chartjs

JS - How to implement the YTD (Year To Date) logic in order to do Date selection


I am trying to implement a method for a Date selection in vue-chartjs. Here is the function that i have used in the methods life cycle hook:

DateSelect(event) {
  const period = event.target.value
  let minValue = new Date(Math.max(...this.date) * 1000)
  const axisXMin = new Date(Math.min(...this.date) * 1000)

  switch (period) {
  case '1m':
    minValue.setMonth(minValue.getMonth() - 1)
    break
  case '3m':
    minValue.setMonth(minValue.getMonth() - 3)
    break
  case 'ytd':
    minValue.setFullYear(minValue.getFullYear() - minValue.getMonth())  //Here I want to implement the YTD Logic.
    break
  default:
    minValue = axisXMin
  }
  const data = this.data.filter(el => {
    return el.x >= minValue
  })
  this.GraphOutput(data) // this is vue-chartjs function.
}

Here the logic '1m' and '3m' works absolutely fine, as they display the previous 1month's and 3month's chart to the user when the respective button is clicked.

I want to know how to implement the YTD (Year to Date) Logic in the function that i have used above. Please do help me.


Solution

  • As far I understand you may need a full year of data in the graph. So that you need to set the minimum value as below:

    case 'ytd':
        minValue.setYear(minValue.getFullYear() - 1);
        break