ChartsOrg / ChartsOrg/Charts

Smarter DateTime Axis Formatter?

Open
#4,832 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Swift
Stars
28k
Forks
6k
PR merge metrics
No merged PRs in 30d

Description

## What did you do?

Code below

## What did you expect to happen?

smarter datetime values on x-axis

## What happened instead?

all empty labels

__________________________________________________

## Problem

I'm trying to override the `AxisValueFormatter` class with a datetime formatter. To show date strings on the x axis labels. There are many examples of this online, but it essentially boils down to: take x-index and push it through a `DateFormatter` that is customised to your desired format.

Running into this issue now where there's a lot of redundancy in the labels... For example why does the chart have to have the following labels:

` "06/02 10:00:00 AM", "06/02 10:00:30 AM", "06/02 10:01:00 AM", "06/02 10:01:30 AM"`

The date is redundant past the first entry if it is the same. So is the hour and minute and second if you ask me....

So I tried to be smart and store the last seen date and only write the date string if it's different... i call it `date_str`, same with the time, i call that `hr_str`.

But for some reason i'm getting empty labels when using the code below, it always assumes it's seen the date+hr before.

Any suggestions on how to fix this?

## Code
```
/// This formatter is used for passing an array of x-axis labels, on whole x steps.
class DateTimeFormatter: NSObject, AxisValueFormatter {

var last_date = ""
var last_hr = ""

func stringForValue(_ value: Double, axis: AxisBase?) -> String {

if value == 0 {

return "Now"
}

let dateFormatter = DateFormatter()
dateFormatter.setLocalizedDateFormatFromTemplate("dd/MM")
dateFormatter.locale = .current
let dt_str = dateFormatter.string(from: Date(timeIntervalSince1970: value))
last_date = dt_str

let hrFormatter = DateFormatter()
hrFormatter.setLocalizedDateFormatFromTemplate("hh:mm:ss")
hrFormatter.locale = .current
let hr_str = hrFormatter.string(from: Date(timeIntervalSince1970: value))
last_hr = hr_str

return "\((last_date == dt_str) ? "" : dt_str) \((last_hr == hr_str) ? "" : hr_str)"
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.