Primefaces LineChartModel: put date in Y axis

1.3k Views Asked by At

I'm using JSF2 and PrimeFaces 5.1.

My problem is that I don't know how to put dates in the Y axis of my graph. It only accepts Number types.

/**
 * Graph's definition
 * @return LineChartModel
 * @throws ParseException
 */
public LineChartModel createLineModels() throws ParseException {
    LineChartModel lineChartModel = new LineChartModel();
    lineChartModel = initCategoryModel();
    lineChartModel.setTitle("Graph's title");
    lineChartModel.setLegendPosition("nw");
    lineChartModel.getAxes().put(AxisType.X, new CategoryAxis("PV"));

    Axis yAxis = this.lineChartModel.getAxis(AxisType.Y);
    yAxis.setTickInterval("1");
    yAxis.setLabel("Provisional dates");
    return lineChartModel;
}

/**
 * Initialization of the graph
 * @return LineChartModel
 * @throws ParseException
 */
public LineChartModel initCategoryModel() throws ParseException {

    LineChartModel model = new LineChartModel();

    ChartSeries provisionalDates= new ChartSeries();
    provisionalDates.setLabel("Dates");

    //Here, I set my data in the Graph
    //In x-axis the date and the y-axis a numerical value
    provisionalDates.set("2016-01-01", 5);
    provisionalDates.set("2016-01-15", 8);

    model.addSeries(provisionalDates);

    return model;
}

My issue are those lines:

provisionalDates.set("2016-01-01", 5);
provisionalDates.set("2016-01-15", 8);

The method set only accept a Numerical value. I want to have date instead.

Do you know a way so I can put my dates in the Y axis?

Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

I finally found an answer with jqPlot.

The method set only accept a numerical value so what I did is to convert my date in milliseconds.

long dateMS= myDate.getTime();
provisionalDates.set("2016-01-15", dateMS);

Then, you can add an extender to your chart with PF. The extender allows you to configure your chart:

model.setExtender("extender"); //Works with PF 5+

After that, you just need to make the extender function:

function extender() {
    this.cfg.axes.yaxis.tickOptions = {
        formatter: function (format, value) {
            return $.jqplot.sprintf(convertDate(value));
        }
    };
}

The convertDate function only convert a getTime to dd/mm/yyyy.

function convertDate(ms) {
    var dateReadable = new Date(ms);
    var year = dateReadable.getFullYear();
    var month = dateReadable.getMonth() + 1;
    if (month < 10) {
        month = "0" + month;
    }
    var day = dateReadable.getDate();
    if (day < 10) {
        day = "0" + day;
    }
    return day + "/" + month + "/" + year;
}