What is the reason for adjusting the time value on my axis in moment.js?

I have been utilizing chart.js and moment.js to display a chart with the x-axis representing time.

Encountered some issues with plotting this axis, so I posted this question.

The problem was resolved by @uminder. Below is the code provided,

var sData = {
  datasets: [{
    label: 'Dataset1',
    data: [{
        x: '09:00',
        y: 88
      }, {
        x: '09:10',
        y: 89
      }, {
        x: '09:13',
        y: 86
      }, {
        x: '09:23',
        y: 86
      },
      {
        x: '09:26',
        y: 85
      }, {
        x: '09:29',
        y: 83
      }
    ]
  }, {
    label: 'Dataset2',
    data: [{
        x: '09:02',
        y: 88
      }, {
        x: '09:13',
        y: 89
      }, {
        x: '09:14',
        y: 86
      }, {
        x: '09:20',
        y: 86
      },
      {
        x: '09:24',
        y: 85
      }, {
        x: '09:29',
        y: 83
      }
    ]
  }]
}

sData.datasets[0].data = formatData(sData.datasets[0].data)
sData.datasets[1].data = formatData(sData.datasets[1].data)

function formatData(oldData) {
  var newData = []
  for (var i = 0; i < oldData.length; i++) {
    var currentData = {}
    currentData.x = moment(oldData[i].x, "HH:mm")
    currentData.y = oldData[i].y
    newData.push(currentData)
  }
  return newData
}

var options = {
  responsive: true,
  scales: {
    xAxes: [{
      type: 'time',
    }]
  },
  tooltips: {
    callbacks: {
      title: (tooltipItem, data) => moment(tooltipItem[0].label).format('HH:mm')
    }
  }
}

var ctx = document.getElementById('bateria_graf').getContext('2d');
let chart = new Chart(ctx, {
  type: 'line',
  data: sData,
  options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.1.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="bateria_graf"></canvas>

However, there seemed to be inconsistencies when running the snippet, as the x-axis displayed differently each time,

https://i.sstatic.net/goWfR.png

The solution provided reflected in my program as shown below,

https://i.sstatic.net/enqih.png

But when using my own datasets, it rendered like this,

https://i.sstatic.net/tpslT.png

Why does the format keep changing? And why is today's date being displayed? I simply require the hour:minute in 24H format.

The datasets I'm passing in the third image are structured like this,

[{
  'label': 'Node1',
  'borderColor': '#4c59b4',
  'data': [{'x': '12:22', 'y': 86}, {'x': '12:32', 'y': 86}, ...]
}, {
  'label': 'Node2',
  'borderColor': '#786f91',
  'data': [{'x': '09:08', 'y': 86}, {'x': '09:19', 'y': 86}, ...}]
}]

Answer №1

To ensure your chart consistently displays time units in the desired format, you can specify the time unit as shown below.

xAxes: [{
   type: 'time',
      time: {
         unit: 'minute'
      }
   }]

Keep in mind that the default display format for the time unit 'minute' is 'h:mm a' (e.g., "11:44 am"). If you wish to define a different format, you can utilize displayFormats.

xAxes: [{
      type: 'time',
      time: {
        displayFormats: {
          minute: 'h:mm'
        }
      }      
    }]

This code snippet provides a runnable example:

var sData = {
  datasets: [/* Data sets here */]
}

sData.datasets[0].data = formatData(sData.datasets[0].data)
sData.datasets[1].data = formatData(sData.datasets[1].data)

function formatData(oldData) {
  var newData = []
  for (var i = 0; i < oldData.length; i++) {
    var currentData = {}
    currentData.x = moment(oldData[i].x, "HH:mm") // Formatting time
    currentData.y = oldData[i].y
    newData.push(currentData)
  }
  return newData
}

var options = {
  responsive: true,
  scales: {
    xAxes: [{
      type: 'time',
      time: {
        unit: 'minute' // Time unit specified
      }
    }]
  },
  tooltips: {/* Tooltips configuration */}
}

var ctx = document.getElementById('bateria_graf').getContext('2d');
let chart = new Chart(ctx, {
  type: 'line',
  data: sData,
  options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="bateria_graf"></canvas>

UPDATE

NEA raised a concern about the output displaying the current date before the time values, which might be misleading. This occurs due to parsing the time using Moment.js.

moment(oldData[i].x, "HH:mm")

If the parsed string lacks date information, Moment.js assumes it belongs to the current date. This assumption is necessary because the parsed object encapsulates a Date. Feel free to run the code snippet below and check the console log for clarification.

const m = moment("11:44", "HH:mm");
console.log(m);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ionic 2 struggles to manage a menu overlaying a Google Maps component

I have developed an Ionic V2 side menu application and incorporated a GMaps element into it. However, I am facing issues with handling elements that appear in front of the map. The buttons on the side menu become disabled when they are overlapped by the ma ...

What is the best way to effectively utilize bootstrap and JavaScript together?

I've been trying to implement some JavaScript on top of Bootstrap 5, but it doesn't seem to be working. I'm not sure if I'm doing something wrong with the JavaScript itself, or if there's an issue with how it's interacting wit ...

Enhancing the angular options list with new commands

Is there an easy way to append specific commands to the end of an Angular select box? For instance, I want a list that looks like this: Cat Dog Octopus Browse… All items except Browse are data values bound using ng-options, while Browse is a command t ...

js Convert a flat array into a nested array using map() and reduce() methods

I have a flat array structured as shown below and I am looking to convert it into a nested array with parent-child relationships. let arr = [ { id: 4, parentId:1, value: 20 }, { ...

Is there a way to dynamically refresh the Bing web API search results on a React.js application after entering a search query in the search bar (in the SER

I've been using the Bing Web Search API to access data by typing a query into a search bar I created. However, I've been facing an issue where the data isn't displaying in the search results when I submit the query. I'm specifically try ...

Issue with XHR progress not functioning properly when cache is not cleared in CHROME

I will provide a detailed explanation of my issue. IMPORTANT-1: This issue arises with large files and under slow upload speed network conditions. IMPORTANT-2: The progress bar functions correctly in browsers like Edge. IMPORTANT-3: The problem only manif ...

A tutorial on submitting multipart/form-data using JavaScript

I am currently facing an issue with the uploadImage API in my frontend. I am using input[type='file'] to obtain image data from users and then POSTing it to my API. In the backend, I am parsing this data using formidable. However, the problem ari ...

Removing the column name from a JSON return in C# involves using a variety of techniques

Below is a JSON output I have received : [ { positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION ...

Can a web application access USB devices across different browsers and operating systems?

I am curious about how we can achieve this particular task. I have heard various things about Silverlight 4, JavaScript, or ActiveX control, but I have yet to see a demonstration of code for any of them. Is there a web component available for this, or is ...

Failed to push an array of objects into another array in JavaScript

In my scenario, I am working with an array of rooms within an asylum. var rooms = [ { "id": 1001, "room": "room 1" }, { "id": 1002, "room": "room 2" }, { "id": 1003, "room": "room 3" }, { ...

The function is not defined after the button is clicked when an if-else statement is added to the

Hello there, I am currently working on a form to submit data to the database using ajax and CodeIgniter. The form seems to work fine for inserting data, but it lacks validation to check whether the fields are empty or not. I am attempting to add an if-else ...

What is the best way to swap out elements within an array?

A server-loaded array with type FilterModel[] is depicted below: export type FilterModel = { title: string; type: FilterType; collection: FilterList; }; export type FilterList = FilterListItem[]; export type FilterListItem = { id: number | ...

Object list with dynamic key names

I have implemented a 'meta' modal box using both bootstrap and angularjs. My current goal is to utilize this setup for saving entered details and sending them to the web API that is running behind the scenes. The functionality works perfectly, bu ...

Having trouble with updating PHP MySQL data using serializeArray?

My HTML page includes a display of temperature with two buttons - one for updating MySQL with the temperature setting and the other for toggling on/off data. Previously, everything was functioning correctly with the initial code: function myFunction() { ...

Getting the state data from a different component in React

Just delving into the world of React and encountered a problem. I have a selector that lets me choose the year/make/model of a vehicle. However, my goal is to reset the make and model if the year is changed, or only reset the model if the make is changed. ...

Encountering difficulties while trying to access the SQLite database file through a JavaScript Axios GET request

Having trouble opening an sqlite DB file from a js axios.get request which is resulting in an exception message being outputted to the console. The request is supposed to call my PHP controller to retrieve data from the DB and return it json-encoded. On t ...

Ways to send a command line parameter to an embedded script?

IMPORTANT: This concerns passing arguments not to the main script, but to a script called by that script When I specify command line arguments directly in my package.json script, it works fine. However, when I call a script that then calls another script, ...

Working with multi-line HTML content within Javascript

I am currently using JavaScript to define the behavior of a button on a website. I want the button to add new HTML content to a specific part of the page, and I would like to use the MVC extension method Html.EditorFor to create this new HTML. Here is wha ...

In React Router version 4, it is stated that each router is only allowed to have a single child element when using multiple routes

I'm currently working on implementing a sidebar alongside the main content area using react-router-dom. Instead of just rendering <Sidebar/> directly, I want to pass it the location prop due to another issue where clicking a <Link/> in the ...

selenium extraction failure

I am attempting to log in to this specific website using selenium. I've imported the web driver and Keys module in order to input my login information into the required fields on the page. from selenium import webdriver from selenium.webdriver.common. ...