0

I believe this question and answer explains how to format time series data into readable date labels in Java. How do you do the same thing in Kotlin?

Ben
  • 3,346
  • 6
  • 32
  • 51

2 Answers2

2

You could create a custom formatter class extending the IAxisValueFormatter:

class MyCustomFormatter() : IAxisValueFormatter 
{
    override fun getFormattedValue(value: Float, axis: AxisBase?): String
    {   
        val dateInMillis = value.toLong()
        val date = Calendar.getInstance().apply {
            timeInMillis = dateInMillis
        }.time

        return SimpleDateFormat("dd MMM", Locale.getDefault()).format(date)
    }
}

Then assign it to your chart with

    chart?.xAxis?.valueFormatter = MyCustomFormatter()
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
  • Thanks, that helped me get on the right track. I had to update the code from the other answer because it does not reflect the latest version of MPAndroidChart – Ben Jan 01 '21 at 00:10
0

Using version 3.0+ of the MPAndroidChart:

Set formatter to the x axis:

// Formatter to adjust epoch time to readable date
lineChart.xAxis.valueFormatter = LineChartXAxisValueFormatter()

Create a new class LineChartXAxisValueFormatter:

class LineChartXAxisValueFormatter : IndexAxisValueFormatter() {

    override fun getFormattedValue(value: Float): String? {
    // Convert float value to date string
    // Convert from seconds back to milliseconds to format time  to show to the user
    val emissionsMilliSince1970Time = value.toLong() * 1000

    // Show time in local version
    val timeMilliseconds = Date(emissionsMilliSince1970Time)
    val dateTimeFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault())
    return dateTimeFormat.format(timeMilliseconds)
  }
}

When the entries are added to the ChartDataArray they are added in seconds, not milliseconds, to avoid potential precision issues with inputting as a float (i.e. milliseconds divided by 1000).

chartDataArray.add(Entry(secondsSince1970.toFloat(), yValue.toFloat()))

Happy coding!

Ben
  • 3,346
  • 6
  • 32
  • 51