Is Unix Mishandling Dates (or Am I Mishandling Dates?)

My data structure consists of different intervals, with the first column representing time in Unix format and subsequent columns showing corresponding values. Here is a snippet of the data:

a1521207300,555.45
1,554.53
2,554.07
3,553.9
4,552.67

To convert this Unix time to a Date object, I removed the ornamental 'a' using slice():

    var rawTime = data[0].interval;
    var timeValue = Math.round(rawTime.slice(1));
    console.log(timeValue)
    console.log(new Date(timeValue))

I also attempted using parseInt() instead of round(). However, it unexpectedly resulted in a January 18, 1970 date. This puzzled me because the expected date should be March 16, 2018. Upon further investigation, I found that JavaScript is capable of directly accepting Unix dates, as seen in this answer.

I cross-referenced the Unix time on an online conversion site at www.onlineconversion.com/unix_time.htm which confirmed it was indeed a timestamp for March 16, 2018.

Question: Despite the correct Unix date for my March 2018 data, why does it show up as a date from the 1970s? Is the 'a' causing this discrepancy? How should I accurately handle this timestamp given that it's only 10 digits long and well within Date's capability range?

Answer №1

According to the resource, utilizing new Date(value) with an integer value denotes the number of milliseconds from January 1, 1970. Adjusting the value to 1521207300 suggests that it is in seconds rather than milliseconds; a factor of 1000 was overlooked. By changing it to new Date(1521207300000), the result is Fri Mar 16 2018.

Removing 'new' from new Date seems to resolve the issue. The reason behind this change remains unclear.

The discrepancy is outlined in the documentation:

Note: JavaScript Date objects can solely be created by utilizing JavaScript Date as a constructor; using it as a regular function (without the new operator) will yield a string instead of a Date object. In contrast to other JavaScript object types, JavaScript Date objects lack literal syntax.

When invoked as a function like Date(value), it interprets the value as seconds rather than milliseconds. Although further investigation on my part was not conducted to validate this, it is insignificant due to the recommendation against this usage in the documentation (in addition to providing a string output rather than a date object).

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

Difficulty with Angular's Interpolation and incorporating elements

I've encountered an issue with String Interpolation while following an Angular course. In my server.component.ts file, I've implemented the same code as shown by the teacher in the course: import { Component } from "@angular/core"; @Component ( ...

What is the process for incorporating a dropdown field and editable field within a container?

Looking to create a unique setup by incorporating dropdown fields and editable text fields within a designated box, similar to the image provided. Any tips on how to successfully implement this design? https://i.sstatic.net/6tGMp.jpg ...

Utilizing AngularJS to showcase and verify a form field populated by JSON data

I am looking to set up a form with validation and a submit button. As a beginner in Angular, I'm not entirely sure where to start. - I need some guidance on what Controller to use or perhaps a starting point. JS: myApp.controller('jsonCtrl&a ...

Tips for preventing a valid instruction from being identified as an error in NetBeans

As I work on my socket.io and node.js system in NetBeans 7.2, I encounter an issue every time I input a correct instruction like: io.sockets.in(channel_id).emit('new user', data); The problem lies in the ".in" part, which triggers an error high ...

A technique, such as regular expressions, can be used to detect the quantity of newline characters in the text entered by the user in a text area

I'm trying to figure out how to count the number of newline characters (or whatever is inserted when the user presses the return key) in a textarea's value. I believe I should be using a regular expression for this task, but I'm not very ski ...

What is the best way to create a toggle effect for a <nav> bar that appears from beneath a div?

I need assistance with a navigation setup where the nav (located inside the header) needs to be connected to the bottom of a div named .menu_bar. The desired behavior is for the nav to slide down from directly underneath the .menu_bar when toggled, but cur ...

Uploading files to an S3 bucket with Node.js

Currently, I am utilizing Sailsjs version 0.12.1 along with node.js 4.2.6 My objective is to upload a file from the front-end (built using angular.js) through an API and then proceed to upload this file to an AWS S3 bucket from the backend. When sending ...

What is the best way to filter out duplicate objects in JavaScript?

I have the following code snippet: let self = this; self.rows = []; self.data.payload.forEach(function (item, index) { if (!(self.rows.includes(item))) { self.rows.push(item); } }); The issue is that includes always returns false. Each ite ...

Angular's Routeprovider: Navigating Your Way through the

I am a newcomer to Angular and I encountered an issue while trying to implement routeProvider in my app. The error message that keeps appearing is: Uncaught Error: [$injector:modulerr] Failed to create module 'app' due to: Error: [$injector: ...

Having trouble loading the URL into an iframe using angularJS

With AngularJS, I am attempting to dynamically load the URL address "myLink" into an iframe in another HTML file. The data.No variable is obtained from elsewhere and functions correctly (providing the necessary ID for the URL). In the controller - "Transa ...

Discover the step-by-step guide to integrating the Oxford Dictionary API with ReactJS!

I am a beginner in the world of React and I'm currently working on creating a dictionary web application. My goal is to utilize the API provided by Oxford dictionary. I have already signed up for the prototype version and obtained my API_ID and API_KE ...

React Context - Ensure synchronized deletion of user posts across routes while maintaining pagination during fetching

INTRODUCTION I am striving to replicate the behavior commonly seen in social networks, where deleting a post by a user results in its automatic removal across all app routes. This functionality is reminiscent of how platforms like Instagram or TikTok oper ...

Implementing a dynamic click event for checkboxes in jQuery specifically targets the first checkbox

Currently, I am dealing with multiple ascx controls that contain different areas with checkboxes on each one. Initially, I utilized the following code snippet: $('[type=checkbox]').click ( function(){ code }); and it worked as intended at firs ...

What are the steps for utilizing a button instead of an input field that is not within a form?

I need assistance with setting up a navbar with a button that will submit a form in the body with the ID of album_form. Can anyone provide suggestions for what to include in the onclick attribute to achieve this functionality? <body> <header& ...

Iterating through an array in Angular with ng-repeat and dynamically adding two elements to a div instead of just one

Utilizing Angular, I have set up a get request to retrieve live data. My goal is to then showcase this data on the home page. Here is the code snippet from my controller: $scope.holder = []; $http.get('url').success(function(data){ $sc ...

Designing scroll boxes that are not continuous and tracking the time spent in each section

I'm seeking assistance with a unique challenge involving the creation of scroll boxes for use in a Qualtrics survey and tracking the time spent viewing different sections of text within them. Specifically, I aim to design a scroll box featuring two p ...

JavaScript appending checkboxes to a list not functioning as expected

I have not been using jQuery, JavaScript, and HTML to create a list of products. The task I am working on now is the ability to select multiple items from this list. Currently, the HTML list is dynamically populated with <li> elements using JavaScri ...

Tips for avoiding $state refresh in Components unaffected by changes to $state.var?

We are currently utilizing Angular-ui-router for managing the state of our application. One issue we are facing is that every component refreshes when there is a change in the $state, even if it's a variable that has been updated and is not used or d ...

The button is failing to accurately update the displayed output

I am currently working on a random quote generator, and I seem to have encountered an issue when the "New Quote" button is clicked. To keep things concise, I have simplified and downscaled the data for the quotes, colors, and animations variables. The prob ...

Collaborating an Ember JS application with a React host through microfrontend integration

While attempting to integrate various frontend technologies within a React host using microfrontends, I successfully connected React, Vue, and VanillaJS applications to the host. However, I've hit a roadblock when it comes to incorporating Ember JS. U ...