Eliminating the use of am/pm and implementing a 24-hour format on the x-axis of a time series

Currently, I am attempting to create a time series plot with second precision in the format of HH:mm:ss (24 hours per day), as indicated in the documentation provided by moment js.

However, I have encountered an issue where the format I specify is not being correctly applied. Despite referencing various combinations from the chartsjs documentation, none of them seem to work.

Vue.component('line-chart', {
  extends: VueChartJs.Line,
  mixins: [VueChartJs.mixins.reactiveProp],
  props: ['chartData', 'timeFormat'],
  data() {
    return {
      options: {
        animation: false,
        scales: {
          xAxes: [{
            type: 'time',
            distribution: 'series',
            time: {
            format: this.timeFormat
            }
          }],
        },
      }
    }
  },
  mounted () {
    this.renderChart(this.chartData, this.options);
  }
})

var vm = new Vue({
  el: '.app',
  data() {
    return {
      chart: {},
      timeFormat: 'HH:mm:ss',
      timeout: null,
      len_data: 20
    }
  },
  created () {
    this.change_data();
  },
  methods: {
    change_data: function() {
      this.chart = this.fillData();
      this.timeout = setTimeout(this.change_data, 1000);
    },
    fillData () {
      return {
          labels: this.get_labels(),
          datasets: [{
            fill: false, // line
            pointRadius: 2, // line
            borderWidth: 2, // line
            borderColor: "rgba(25, 25, 125, 1)",
            data: this.get_nums(0),
            label: "Points"
          }]
        }
    },
    get_labels()  {
    return Array.from({length: this.len_data}, (v, k) => this.newDateString(this.len_data-k)); 
    },
    get_nums(data_idx) {
      if(typeof this.chart.datasets !== 'undefined') {
      this.chart.datasets[data_idx].data.shift(); // removing the first item
        this.chart.datasets[data_idx].data.push(this.getRandomInt()); // adding a new one
       return this.chart.datasets[data_idx].data;
      }
      return Array.from({length: this.len_data}, (v, k) => this.getRandomInt());
    },
    getRandomInt () {
      return Math.floor(Math.random() * (50 - 5 + 1)) + 5
    },
    newDateString(seconds) {
      return moment().subtract(seconds, 's').format(this.timeFormat);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3d5d6c68ec0cbc2d1d7c9d0e3918d958d96">[email protected]</a>/dist/vue-chartjs.full.min.js"></script>

<div class="app">
  <line-chart :chart-data="chart" :time-format="timeFormat" width="400" height="200"></line-chart>
  <br>{{chart.datasets[0].data}}
</div>

Almost there, just missing a small detail. Could use some guidance.
Check out the JSFIDDLE for reference: https://jsfiddle.net/ue1x8079/

Answer №1

The Documentation for Chart.js provides the following structure for formatting time axes labels:

time: {
    displayFormats: {
        quarter: 'MMM YYYY'
    }
}

By implementing your specified format, it would look like this:

time: {
    displayFormats: {
        second: this.timeFormat
    }
}

You were spot on, just a minor adjustment! (Updated Fiddle link).

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

The HTML drag and drop API is causing an issue where the `getData`

My website features a drag-and-drop functionality, and I'm utilizing the HTML drag-and-drop API to implement it. However, when I attempt to drag and drop an SVG image onto the canvas, it displays as undefined, and I would like the image to remain in t ...

Create a polling feature using a Grease Monkey script

I am looking for a way to run a Tamper Monkey script on a Facebook page that regularly checks a database for new data and performs certain actions. I have attempted to implement polling using AJAX, and below is the code I used: (function poll() { setT ...

Combining Option Value and Name Selection Using React Hooks

Currently, I am facing a situation where I need to retrieve two different values (item.id and item.name) to set the State when selecting an item from my dropdown menu. Right now, I am only able to do this for one value (item.id). Is it possible to achieve ...

The Journey of React Native Routing

When building my React Native application, I encountered a challenge with creating a Footer and Tab menu that should only be displayed on certain screens. If I define them within the NavigationContainer, they apply to all screens uniformly. How can I sep ...

What could be causing the Universal Code for Disqus to not function properly?

Struggling to get this code to work on my website. I've tried everything, from clearing caches and cookies to disabling plugins and extensions, but still no luck. Check out the code below: import React, { Component } from 'react' import { ...

Closing a dropdown menu when opening another one

As a beginner in Vue.js, I am currently working on a CRUD project for my coursework. One issue I am facing is with the behavior of the dropdown menu. Can anyone provide assistance? https://i.sstatic.net/1MozuN3L.png I have specific requirements: The dr ...

When using REACT to fetch data from an API, the absence of an 'Access-Control-Allow-Origin' header may result in access issues

I am working on a project that involves retrieving products from a company's API. After reaching out to the company, they provided me with the following information: CORS allowed origins for local development is "http://localhost:1229" To adhere t ...

The StateProvider is giving back an iteration that is undefined

AppContext.js import React, { createContext, useContext, useReducer } from "react"; // Initialize the appContext export const AppContext = createContext(); // Wrap the app and set up the App Context export const AppProvider = ({ reducer, initia ...

Having trouble extracting the date modified from a JSON file

I am able to retrieve section name, URL, web title, and headline from parsing JSON data with this code snippet. However, I seem to be encountering an issue where I cannot extract the last modified date. Here is the JSON structure: { "response":{ ...

Establish a universal default component for Vue route configurations

How can I load the component of a specific route in my Vue application within a global component? For example, is there a way to set a global component that will display the components of all routes? I have a Frontend.vue file with <router-view>< ...

Utilizing Node.js for Lambda Functions

I am attempting to retrieve a list of all EC2 instances in a specific region using a lambda function. Below is the code snippet I am using: const AWS = require('aws-sdk'); AWS.config.region = '******'; exports.handler = async function( ...

The functionality of sending form data via Express.js router is restricted

In my current project, I am developing a basic CRUD functionality in express. My goal is to utilize the express.Router() to transmit form data via the HTTP POST method. The form structure on the browser appears as follows: form.png The process was flawle ...

Passing arrays to a Vue component in a static manner

I am trying to pass an array statically to my Vue component named ajax-table. After struggling to find a solution, I decided to use the following approach: <ajax-table header-names="Code, Name, Description, Type" field-names="code, name, descri ...

What is the most efficient way to save a document in mongoose based on a specific user's

Is there a way to ensure that when saving a template, it is associated with the user id? I have added a reference to the templateSchema for the User. User.model.js var UserSchema = new mongoose.Schema({ _id: { type: String, required: true, index: {uniq ...

React - Login page briefly appears while loading

Hello, I have built a React application that consists of a Login page, Loading page, and the main app itself. However, there is a small issue where after a user logs in, instead of smoothly transitioning to the Loading page until the data is loaded, the L ...

Creating a responsive DataTable filled from a $.ajax request is a straightforward process that can greatly

I am in the process of creating an application that retrieves a lot of data from a web-service query and populates a data table with it. The data shows up correctly and styled properly on desktop, but when I switch to viewing it on a mobile device, the dat ...

Set YouTube Playlist to start from a random index when embedded

I've been trying to figure out how to set my embedded playlist to start with a random video. Here's what I attempted: <iframe src="https://www.youtube.com/embed/videoseries?list=PLPmj00V6sF0s0k3Homcg1jkP0mLjddPgJ&index=<?php print(ran ...

How Vue.js seamlessly handles self-dismissing alerts using the Vuex store

I am struggling to automatically dismiss my alerts in the correct order. Currently, I am storing the alerts in Vuex and generating them through actions. The problem arises when there are multiple alerts, as they should be dismissed based on the sequence of ...

Error: The function call does not match any of the overloads. 'VueRouter' is not recognized

I'm new to TypeScript and currently trying to implement vue-router in my project. Encountering the following errors: Error TS2769: No overload matches this call in source\app\main.ts(3,3). Overload 1 of 3, '(options?: ThisTypedCompon ...

Is a Javascript-only application compatible with Amazon S3 cloud storage?

I am currently investigating the validity of the following statement: Based on my research, it seems unlikely to create a web application using only JavaScript - without any server-side logic - hosted on Amazon S3 that can also store data solely on S3 whi ...