0

Currently the DateTime is being read into chart.js from a SQL database using this line of code:

var XLabels = Newtonsoft.Json.JsonConvert.SerializeObject(Model.Select(x => x.DateTime).ToList());

The format of the DateTime is shown like this:

2019-05-14T15:30:02.703

I would like for the T to be removed as well as the milliseconds from this as it's making the graph look messy.

I currently have the data also reading into a table and it appears like this:

12/04/2019 23:01:01

This is how I would like it to appear in the charts as well.

demo
  • 6,038
  • 19
  • 75
  • 149
BFieldy
  • 1
  • 2
  • Remove it on the client side, where you are reading/deserializing json data – Fabio May 15 '19 at 10:48
  • Just look intothis https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1 – Narendran Pandian May 15 '19 at 10:48
  • https://www.chartjs.org/docs/latest/axes/cartesian/time.html – demo May 15 '19 at 10:54
  • `DateTime` has no format at all. It's a binary value, just like byte or int. Formats apply *only* when it's converted to a string, or parsed from a string. The defacto standard for date *strings* in JSON is ISO 8601, ie `2019-05-14T15:30:02.703` which Javascript has no trouble using and parsing into its own `Date`. – Panagiotis Kanavos May 15 '19 at 10:56
  • If you want to change how a *chart* works, you'll have to modify the *chart's* settings. What does your Javascript code look like? Have you set a format string for the X labels? – Panagiotis Kanavos May 15 '19 at 11:00
  • [This possibly duplicate](https://stackoverflow.com/questions/20371867/chart-js-formatting-y-axis) question shows how to format axis labels using your own function – Panagiotis Kanavos May 15 '19 at 11:02

1 Answers1

1

Welcome.

Try formatting it like this to get your output as you require:

DateTime.Now.ToString("dd/MM/yy HH:mm:ss")

Did you try searching this in the stack overflow or google before putting the question up here? In the future, try searching out as this is a duplication of couple of questions like these: C# DateTime to "YYYYMMDDHHMMSS" format

You should be able to make your own answers from them. Have a nice day.

demo
  • 6,038
  • 19
  • 75
  • 149
  • Thanks, I was converting to datetime and it was causing the formatting issue. – BFieldy May 15 '19 at 10:54
  • 1
    @BFieldy DateTime has no format, it's a binary value. JSON has a defacto standard date format, ISO8601. You'll get into trouble only if you try to use your own non-standard format – Panagiotis Kanavos May 15 '19 at 10:57