Javascript encounters difficulty in converting timestamp to a date format

I am utilizing this particular function

export const getDate = (stamp: string) => {
    console.log(stamp) //1581638400000
    let date : any = Date.parse(stamp)
    console.log(date) //NaN
    let month = date.getMonth()
    let day = date.getDay()
    let year = date.getYear()

    let formattedTime = month + '/' + day + '/' + year
    return formattedTime
}

However, it appears to be functioning properly on this website

https://i.sstatic.net/6PC4R.png

What's the issue here? Why am I unable to use that timestamp?

Answer №1

To correctly convert a date, make sure to use the new Date() method. The Date.parse() method expects a string input, not a number.

In addition, ensure that the date format is correct:

The getDay() function returns the day of the week as a number between 0 and 6. Use getDate() instead, which gives a number between 1 and 31.

Keep in mind that the getMonth() function starts counting from 0.

Lastly, avoid using the deprecated getYear() method. It is recommended to use getFullYear() instead.

Here's an example demonstrating the correct date conversion:

const getDate = (stamp) => {
  console.log(stamp);
  let date = new Date(stamp);
  console.log(date);
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let year = date.getFullYear();
  let formattedTime = month + '/' + day + '/' + year;
  return formattedTime;
}

console.log(getDate(1581638400000));

Answer №2

let timestamp = "1581638400000"
const displayDate = (timestamp) => {
    console.log(new Date(Number(timestamp))) ;//1581638400000
    let dateObj = new Date(Number(timestamp));
    console.log(dateObj); //NaN
    let month = dateObj.getMonth();
    let day = dateObj.getDay();
    // let year = date.getYear(); Deprecated!!!
    let year = dateObj.getFullYear();

    let formattedDate = month + '/' + day + '/' + year;
    console.log(formattedDate);
    return formattedDate;
}

displayDate(timestamp)

Answer №3

let currentDate = new Date(timeStamp * 1000); // multiply by 1000 for milliseconds

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

Exploring the capabilities of JW Player 6 for seeking and pausing video

Is there a way to make JW Player 6 seek to a specific point and pause without pausing after each seek request, maintaining the ability to seek continuously during playback? The current solution provided pauses the player after every seek request, which is ...

The integration of angular-chart.js with generator-angular-fullstack is not supported

Recently, I decided to incorporate Angular into my project by utilizing the angular-fullstack generator (available at https://github.com/angular-fullstack/generator-angular-fullstack). My intention was to use the angular-chart-js library (https://github.c ...

Bring in content using transclusion, then swap it out using AngularJS

I am looking to develop a custom directive that will transform : <my-overlay class="someOverlay"> <h4>Coucouc</h4> </my-map-overlay> Into : <div class="someOverlay default-overlay"> <h4>Coucouc</h4&g ...

Is there a way to execute a script during every npm install process?

Is it possible to set up pre-push hooks for Git with each npm install action? Are there any alternative solutions that do not involve installing tools like Gulp, and instead rely solely on npm? ...

The declaration of 'exports' is not recognized within the ES module scope

I started a new nest js project using the command below. nest new project-name Then, I tried to import the following module from nuxt3: import { ViteBuildContext, ViteOptions, bundle } from '@nuxt/vite-builder-edge'; However, I encountered th ...

Potential Scope Problem in Angular JS Controller

The HTML code snippet I have is as follows: <body ng-controller = "Control as control"> <button ng-click = "control.prepareAction()">Do Action </button> <div id="one" ng-hide = "!control.showOne" > <div> <h6> ...

Unable to extract all advertisements from Facebook Marketplace

https://i.stack.imgur.com/xEhsS.jpg I'm currently attempting to scrape listings from Facebook marketplace, however, only the first listing is being scraped. Does anyone have any suggestions on how I can scrape the entire list of listings? CODE (async ...

Add unique styles to a jQuery-included HTML document

I'm attempting to use jQuery to load an HTML page into the main body of another page. Specifically, I have a div called sidebar_menu positioned in the middle of the page, and I am loading content at the bottom using jQuery. $("#sidebar_menu").load(" ...

How can I loop through an object in React using TypeScript?

This is specifically for React. Let's consider the following object structure: interface Profile { name: string; title: string; } const NewPerson: Profile = { name: "John Smith", title: "Software Engineer" } Now, I want to display ...

Middleware in Redux Toolkit is ineffective in managing successful asynchronous actions

After integrating my own middleware into the Redux-Toolkit store using configureStore in my Next.js app, I noticed that the middleware functions appear to be greyed out. I added them via: getDefaultMiddleware({ thunk: { extraArgument: updateNavTabMid ...

The name 'Queue' cannot be located in Typescript, error code ts(2304)

I'm currently trying to create a private variable of type InnerItem, but I keep encountering the following error: Error: Cannot find name 'Queue'.ts(2304) private savedItems: Queue<InnerItem> = new Queue<InnerItem>(20); Could ...

How can you create a table cell that is only partially editable while still allowing inline JavaScript functions to work?

Just a few days back, I posted a question similar to this one and received an incredibly helpful response. However, my attempt at creating a table calculator has hit a snag. Each table row in a particular column already has an assigned `id` to transform t ...

Is it possible to modify an element within a list based on the identifier of its containing div?

I have created some additional software for my project, which includes a large div with smaller divs inside. Here is an example of how it is structured: <div class="scroll-area" id="lista"> <div class="box" id="item1"> < ...

Traversing a two-dimensional array backwards in JavaScript

I am working with an array that contains different teams: The structure looks like this: leagues = new Array( Array('Juventus'), Array('Milan'), Array('Inter')); My goal is to iterate through the array and generat ...

"AngularJS fails to pass the value of a checkbox within ng-repeat and

I have already asked this question, but the previous solutions did not resolve my issue. I am attempting to pass the value of a checkbox to a controller in AngularJS, but I keep getting an 'undefined' message. I am new to AngularJS. Here is the ...

I am looking for an Angular Observable that only returns a single value without any initial value

Is there a way to create an Observable-like object that calls a webservice only once and shares the result with all subscribers, whether they subscribe before or after the call? Using a Subject would provide the result to subscribers who subscribed before ...

Obtain the identification numbers from the row within the table

I have a table displaying an email Inbox (see excerpt screenshot here). When the user clicks on a checkbox, I need to populate two dropdowns with the correct items. function fnHandleSelectCBClick(cb) { try { var tableRow = $(cb).parent().par ...

NetSuite - Custom Fields - Linked to Address Book but Inaccessible through JavaScript

Currently in the process of creating a Sales Order script to extract a custom field linked to the chosen shipping address. While I have successfully retrieved all address fields (such as city and zip), I am facing challenges when attempting to access any c ...

Error: Headers cannot be set after they have already been sent, resulting in an Unhandled Promise Rejection with rejection id 2

I'm a beginner with Node.js and I've been using express.js. In a section of my code, I'm trying to retrieve data from a form via AJAX and store it in a variable called url. I have access to request.body, but I'm encountering an issue wh ...

The most effective way to export ThreeJS models to Blender

I found a bedroom object on Blender that I downloaded from this source. When exporting it in json format to load it into Three.js, I noticed that only one mesh of the bed component was included instead of all the meshes I had selected. All components of ...