Search code examples
javaandroidmpandroidchart

MPAndroid Date Formatting and Parsing Loses Precision


I'm using the MPAndroid library for the graph of my android app. I have a long value inputted to the entry. My problem is that when I format the values of x axis, it uses float value instead of long so it loses precision.

Here is my code for the entry to the graph:

String dateString = "02/13/2019(11:23:45)";
long readingDate = 0;
try {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy(kk:mm:ss)", Locale.US);
    Date date = sdf.parse(dateString);
    readingDate = date.getTime();
    } catch (ParseException e) {
         e.printStackTrace();
    }
SensorData.add(new Entry(readingDate, 1.5);

Here is my code for formatting the x axis:

private class XAxisValueFormatter implements IAxisValueFormatter {

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        String dateString = new SimpleDateFormat("MM/dd/yyyy(kk:mm:ss)", Locale.US).format(value);
        return dateString;
    }
}

How can I fix this problem?


Solution

  • One of possible solutions would be to make your first point hold 0 value.

    Basically you need subtract start_timestamp from every new x value of Entry so chart will be started from 0 value and not of timestamp.

    For example.

    Let's assume start_timestamp variable holds your first timestamp of datapoints.

    To add new entry use:

    SensorData.add(new Entry(readingDate - start_timestamp, 1.5);

    To format x value you just add start_timestamp to provided x value.