我相信 this question and answer 解释了如何在 Java 中将时间序列数据格式化为可读的日期标签。你如何在 Kotlin 中做同样的事情?
答案 0 :(得分:2)
您可以创建一个扩展 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)
}
}
然后将其分配给您的图表
chart?.xAxis?.valueFormatter = MyCustomFormatter()
答案 1 :(得分:0)
使用 MPAndroidChart 3.0+ 版:
将格式化程序设置为 x 轴:
// Formatter to adjust epoch time to readable date
lineChart.xAxis.valueFormatter = LineChartXAxisValueFormatter()
新建一个 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)
}
}
当条目添加到 ChartDataArray 时,它们以秒为单位添加,而不是毫秒,以避免输入为浮点数(即毫秒除以 1000)时潜在的精度问题。
chartDataArray.add(Entry(secondsSince1970.toFloat(), yValue.toFloat()))
快乐编码!