How can I convert a UTC time field from MySQL into JavaScript?

I'm struggling to pinpoint the error in my date/time difference calculations. It seems to be related to timezone variations, but I can't figure out exactly where the problem lies. Below are all the components involved - can you help me identify the mistake? Many thanks!

Firstly, I verified the mysql timezone settings:

mysql> SELECT @@global.time_zone, @@session.time_zone;
+--------------------+---------------------+
| @@global.time_zone | @@session.time_zone |
+--------------------+---------------------+
| SYSTEM             | SYSTEM              |
+--------------------+---------------------+

On my local machine running macOS, the Date & Time settings are configured with the correct local time and Copenhagen timezone (CEST).

In my mysql database, I have a field defined as:

token_time_utc DATETIME DEFAULT NULL

To populate this field, I use NodeJS and the mysql2 connector like so:

'UPDATE `account` SET token = ?, token_time_utc = UTC_TIMESTAMP() WHERE user_id = ?', [token, account.user_id] ...

After sending an email with the token, I attempt to validate that it was received within 6 minutes, but encounter failure:

// Is the token validation done within 6 minutes based on UTC time?
let sixMins = (60 * 1000 * 6);
let tokenTime = account.token_time_utc.getTime();
let tokenExpiration = tokenTime + sixMins;
let now = new Date().getTime();
console.log('Account timestamp: ' + account.token_time_utc + ' Token time: ' + tokenTime + ' Token expiration: ' + tokenExpiration + ' Now: ' + now
    + ' Diff: ' + (now - tokenTime) + ' Diff (minutes): ' + ((now - tokenTime) / 1000 / 60));
if (now > tokenExpiration) {
    // return error
    res.status(401).json({ message: 'Token timed out' });
    return;
}

The console output reveals:

Account timestamp: Tue May 07 2024 07:25:52 GMT+0200 (Central European Summer Time) Token time: 1715059552000 Token expiration: 1715059912000 Now: 1715066768248 Diff: 7216248 Diff (minutes): 120.2708

This entire process occurs locally on my machine. At the time of execution, it was 9:25 am in Copenhagen, which is currently at GMT+2. The discrepancy of 120 minutes appears to stem from incorrect timezone handling. Despite attempting to adhere to UTC throughout, the DB stored the accurate UTC time relative to mine (7:25 am), yet annotated it with CEST for Copenhagen (which puzzles me).

Could the issue lie in how the time is submitted to the DB using the UTC_TIMESTAMP() command, or perhaps in the utilization of account.token_time_utc.getTime()? Alternatively, could there be mistakes in my usage of JS Date methods?

Should I consider configuring mysql timezone settings? I came across these discussions, but I'm unsure if they address my specific problem: Should MySQL have its timezone set to UTC? How do I set the time zone of MySQL?

Answer №1

The error originates from the fact that Date.now() or new Date() take into account the timezone offset related to the environment (process.env.TZ, if no other timestamp information is provided), whereas UTC_TIMESTAMP() disregards the timezone. It is advisable to use CURRENT_TIMESTAMP() when storing the timestamp or alternatively, configure the node server TZ to UTC as well.

mplungjan's suggestion to add Z to token_time_utc could also resolve the issue.

An alternative approach would be to utilize Date.UTC() and provide the components from the UTC Timestamp to it.

This process can be achieved like so:

const [str, year, month, day, hour, minute, seconds, ms] = 
  '2003-08-14 18:08:04.123'.match(
    /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/
  )
console.log(
  new Date(Date.UTC(year, month -1, day, hour, minute, seconds, ms)).toLocaleString()
)

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

Refresh inventory levels for current product sizes when adding them to the cart

Something seems off with my code. The product stocks are updating, but once I hit the Add button and refresh the page, the added product's stocks disappear. Any ideas on what might be causing this issue? This is the query I am using: if(isset($_POS ...

Using Javascript to upload an image and show it in a small display

Hey there, I have a functioning JavaScript code that loads an image uploaded by the user onto the HTML page. However, the issue is that the image doesn't have a set maximum height or width, causing buttons on the page to move out of view and become in ...

reCAPTCHA v3 - Alert: There are no existing reCAPTCHA clients available

After coming across a similar issue on Stack Overflow (link to the question here), I attempted to implement reCAPTCHA on my website to combat spam emails received through the form. Despite following Google's instructions, I encountered an error that p ...

The IE9 confirmation dialog fails to pause for user response, resulting in automatic postback before user input is received

Behind the Scenes btnNext.Attributes.Add("onclick", " return Verification(this,'" + GetLocalResourceObject("message").ToString() + "'); ") .ASPX Page [Within javascript tags] function Verification(source, message) { var dialog = '< ...

creating a Vue app using Node results in an HTML page with no content due to syntax errors

After creating a VueJs page using the CLI, I wanted to share it with others who might not have Vue CLI or Node installed. Just like opening .html files in a browser, I tried to open the index.html file after building it. However, when I opened the file, a ...

Text randomly appears on the html page

I've been dedicating a significant amount of time to finding a solution, but haven't had any luck. I'm aiming to create a visual effect where 10 words with varying font sizes slide in from different directions on a canvas within my document ...

Steps to activate an event when Windows is loaded

Every time windows load, I want to run $('select[name="order_id"]').change(), but it's not working as expected. After debugging in the browser console, I can see that the script $('select[name="order_id"]').cha ...

Making changes to a JSON file using JavaScript

Hello everyone, I am a beginner in Javascript and have successfully created a system that allows me to search and filter users in my data.json file. However, I am now looking to develop an application that can add users to the data.json file. Any advice or ...

Insufficient allocation - memory overflow in loopback.js

I encountered an issue while trying to fetch large data using loopback.js. The error message I received was: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory <--- Last few GCs ---> 45903 ms: Mark-sweep 1385.6 (14 ...

Error encountered while implementing onMutate function in React Query for Optimistic Updates

export const usePostApi = () => useMutation(['key'], (data: FormData) => api.postFilesImages({ requestBody: data })); Query Definition const { mutateAsync } = usePostApi(); const {data} = await mutateAsync(formData, { onMutate: ...

Transferring information within React components

Looking for some assistance with the code below. I'm facing an issue where the data is not being submitted along with the form, even though the correct values are displayed in the form. I have included a user query to fetch data from another object an ...

Can you determine the worth of a particular search inquiry?

Recently, I developed a system that ranks players based on their points. However, the method through which the points are obtained has proven to be rather perplexing. After utilizing this system for more than 24 hours, it became evident that it was not pro ...

Passing parameters as an array in Angular can be done by using the format: ?category[]=1&category[]=2&category[]=3,

Struggling to send an array using the $http.get() method in AngularJS. Here's my current approach: $http.get('/events.json', {params: {category_id: [1,2]}}); While I anticipate the request to be sent as /events.json?category_id[]=1&cat ...

Retrieve the full directory path that has been chosen in an HTML form

I am facing a similar issue in my web application where I am using PHP, HTML, and JavaScript. What I want is to be able to select a folder and obtain the full path of that folder for backing up data. For example, when a user enters backup.php, they should ...

Retrieving results from PostgreSQL database using pagination technique

When I'm pagination querying my data from a PostgreSQL database, each request involves fetching the data in this manner: let lastNArticles: Article[] = await Article.findAll({ limit: +req.body.count * +req.body.page, or ...

Preventing autoscrolling in Ionic's dual side menu template when additional content is added

Could anyone kindly assist me in figuring out why the autoscrolling of the content is not functioning correctly? Whenever the button on the header is clicked, a new message will be included in the main content. However, once the number of lines exceeds wha ...

Classic design of the shadow element

I have main.js and index.html below class CustomTagA extends HTMLElement { constructor() { super(); const shadow = this.attachShadow({mode: 'open'}); const wrapper = document.createElement('h1'); ...

Synchronously executing Twitter posts

Hello there! I've been using this code found here to embed Twitter posts on my website. It's been working perfectly on certain pages, like in the forums, but I've run into an issue while browsing through user profiles. The post history for e ...

Convert HTML templates into JavaScript on the client side using Angular framework along with Browserify, Babel, ES2015, and Gulp

Having trouble with my Browserify Angular configuration file, specifically when using require() to load HTML templates. I attempted to use stringify or browserify-ng-html2js in the transform() function, but it resulted in multiple transform calls in my gul ...

Error: Unable to access the 'map' property of an undefined object......Instructions on retrieving a single post

import React,{useEffect, useState} from 'react' //import {Link} from 'react-router-dom' import { FcLikePlaceholder, FcComments } from "react-icons/fc"; const SinglePost = () => { const [data,setdata] = useState([]) co ...