Configuring timezone for 'date' type in Plotly.js

I'm currently working on a graph to showcase the trend over time. The data I have is in Unix format and I use JavaScript code (new Date(data)).toUTCString to display it in my title. Surprisingly, while the data for the graph and the title is the same, the graph seems to be running 1 hour ahead of the expected time. You can view an image here.

Below is the layout configuration I am using:

layout = {
    "showlegend": true,
    "title": new Date(min).toUTCString() + " to " + new Date(max).toUTCString(),
    "xaxis": {
        "autorange": true,
        "range": [
            min,
            max
        ],
        "title": "Time",
        "type": "date"    //if I change this to scatter, I get the Unix values
    }

}
 Plotly.newPlot('graphMain', temp, layout); //temp contains the arrays

Currently, I am based in Austria (UTC+01:00 timezone). Does anyone have any insights or suggestions on how to resolve this issue?

Answer №1

Unfortunately, Plotly does not have support for timezones at this time.

If you require datetime calculations in a specific timezone or in UTC, consider using a library like moment.js timezone. Alternatively, you can handle the conversions manually.

Answer №2

Currently, it seems that Plotly.js does not have built-in support for timezones. After some searching, I came up with a workaround solution. However, if you have a better approach, I would love to hear about it!

I assume the dates are originally formatted as yyyy-mm-ddTHH:MM:SSZ. To modify the format, you can utilize the function found at , which fetches the timezone of the user's computer.

function fmt(date, format = 'YYYY-MM-DD hh:mm:ss') {
  const pad2 = (n) => n.toString().padStart(2, '0');

  //These functions retrieve the date from the browser's timezone, such as 'Europe/Madrid'
  const map = {
    YYYY: date.getFullYear(),
    MM: pad2(date.getMonth() + 1),
    DD: pad2(date.getDate()),
    hh: pad2(date.getHours()),
    mm: pad2(date.getMinutes()),
    ss: pad2(date.getSeconds()),
  };

  return Object.entries(map).reduce((prev, entry) => prev.replace(...entry), format);
}
> date = '2022-12-15T10:00:00Z'
'2022-12-15T10:00:00Z'
> newDate = new Date(date)
2022-12-15T10:00:00.000Z
> fmt(new Date(date))
'2022-12-15 11:00:00'

Keep in mind, if you are working with Unix time, this method will also be applicable

> date = 1671100918000
1671100918000
> newDate = new Date(date)
2022-12-15T10:41:58.000Z
> newDate.toLocaleString('se-SE', { timeZone: 'Europe/Madrid' })
'2022-12-15 11:41:58'

To adjust your array of dates to your timezone using the dates variable, you can follow these steps:

> const tz_dates=dates.map(date=>fmt(new Date(date)))

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

A unique Javascript feature that switches the text on various buttons

As someone who is relatively new to Javascript and web development, I am currently working on a project that involves creating multiple text areas for users to input and save text. Each text area is accompanied by a button with a unique ID that functions a ...

I have been unable to find a solution for the non-functioning jQuery (3.4.1 / 3.3.1) load() issue

I have been working with jQuery's .load() function Take a look at my code snippet: <html> <head> <meta charset="utf-8"> <title>load demo</title> <script src="https://code.jquery.com/jquery-3.4.1.js"> ...

"Exploring the process of making a REST call from an Angular TypeScript client to

I'm currently developing a Sessions Server for a project at work. My dilemma lies in the fact that I'm struggling to find resources on how to make JavaScript HTTP calls from a server running with http.createServer() and server.listen(8080, ...) ...

Are there any guidelines or rules outlining what is still considered valid JSONP?

I am looking for information on how to properly parse JSONP messages in .NET and extract the JSON data they contain. Is there a current specification that outlines what constitutes a valid JSONP message? During my research, I came across a blog post from ...

Is it possible to incorporate a React app as a component within a static HTML page?

Looking to integrate the react-csv-viewer component into a static HTML page without deploying it on a local server. I've tried following the instructions from the React tutorial, but am struggling with the build process. My goal is simple - to use th ...

Trouble with AJAX GET request functionality

I am new to AJAX and attempting to make my first AJAX call. Here is the code I have so far: $.get( "validate.php", { 'userinput':'x'}, function(response) { if( response.status ) alert( "Matches found" ); else alert( "No matches ...

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...

Experiencing an anonymous condition post onChange event in a file input of type file - ReactJS

When using the input type file to upload images to strapi.io, I noticed that an unnamed state is being generated in the React dev tools. Can someone explain how this happened and how to assign a name to that state? https://i.sstatic.net/ZyYMM.png state c ...

The contents of the multi-level navigation are automatically shown as the page loads

I've implemented a multilevel dropdown menu on my website using a plugin, and it works as expected. However, there's an issue where the contents of the dropdown menu display for a brief moment while the page is loading. I tried adjusting the posi ...

Accepting insecure certificates in Chrome with Selenium-Webdriver in JavaScript: A Step-by-Step Guide

After generating a test script using Selenium-IDE in Javascript-Mocha format, I encountered an issue with an insecure certificate when trying to access a remote URL locally. To address the problem, I need to modify the generated TestScript to include Chro ...

Incorporate JSON data to display SVG images

As a beginner in web development, I have been honing my skills with the AngularJS framework due to its user-friendly nature. Currently, I'm working on pulling JSON data from an API using $http.get method. One of the fields contains an image source i ...

Can you explain the meaning of arguments[0] and arguments[1] in relation to the executeScript method within the JavascriptExecutor interface in Selenium WebDriver?

When utilizing the executeScript() method from the JavascriptExecutor interface in Selenium WebDriver, what do arguments[0] and arguments[1] signify? Additionally, what is the function of arguments[0] in the following code snippet. javaScriptExecutor.ex ...

Discovering the specific object ID that triggered an event in JavaScript

I am developing a webpage that includes JavaScript functionality. There is a specific function in the Javascript code which gets triggered by two different elements when clicked: 1. When a checkbox is clicked: $('#chkShowAll').click( functi ...

What is the best way to create reusable Javascript code?

Lately, I've adopted a new approach of encapsulating my functions within Objects like this: var Search = { carSearch: function(color) { }, peopleSearch: function(name) { }, ... } While this method greatly improves readability, the challeng ...

Having trouble with Bootstrap's "hidden-xs" class not working and struggling to create a sticky footer for small viewports

Trying to tackle the challenge of making my footer stick to the bottom of the page on smaller screens has been quite troublesome. As a temporary fix, I decided to experiment with hiding the div entirely until I figure out a proper solution. The HTML < ...

Executing the collection.find() function triggers an internal server issue and eventually leads to a timeout error

My ExpressJS backend was running smoothly with hardcoded data, but when I integrated MongoDB into the system, my requests for data started timing out. I added a record to a collection using the command prompt: > db stackmailer > db.sites.find() { ...

Opencart: The Key to Your Website's Success

Quick question - I have a Java snippet that needs to be added to my OpenCart checkout page before the closing </body> tag. However, I cannot locate the </body> tag in the checkout.tpl file of OpenCart. Can anyone guide me on where to find thi ...

What steps can be taken to halt an ongoing AJAX call and initiate a new one with different parameters?

I recently implemented an ajax call using the jQuery.everyTime() function. The setup involves a combo box where users can select different graph names, triggering dynamic calls to an ajax function that returns JSON data and populates a chart in the View ev ...

Having issues with Vue.js and the splice method not functioning properly on an array row

Having an Object array, I noticed that when I try to remove an object from the array list, only items are deleted from the end. <div class="hours" v-for="(time, index) in hour" :key="index"> So, I decided to place a cli ...

Personalized service implemented in Angular's .config settings

I've come across a few examples of how to insert custom providers into angular's .config, but I'm struggling to do it correctly. Here's the provider I have: (function() { var app = angular.module('application.providers', [& ...