Converting Unix time to yyyy-mm-dd format using JavaScript

Can someone assist me with converting Unixtime to a specific date format? Check out my current code below:

var date = "2014-05-01";
var indexPie = Date.parse(date);

I want indexPie in the yyyy-mm-dd format. However, when I try this line of code:

var newDate = new Date(indexPie);

The output shows:

Wed Apr 30 2014 18:00:00 GMT-0600 (Mountain Daylight Time)

But what I actually need is:

Thur May 01 2014 18:00:00 GMT-0600 (Mountain Daylight Time)

Any idea why new Date(indexPie) gives April 30 and how can I achieve my desired format of yyyy-mm-dd?

Your suggestions would be highly appreciated. Thank you.

Answer №1

I successfully tackled the problem by implementing the following solution:

const currentDate = new Date(indexPie);
const year = currentDate.getUTCFullYear();
const month = currentDate.getUTCMonth() + 1;
const day = currentDate.getUTCDate();
const formattedDate = year + "-" + month + "-" + day;

Answer №2

It may appear that the value stored in the date variable: "2014-05-01" is being parsed in local timezone, when it is actually being parsed in UTC.

To convert the date from UTC to local timezone, use the following code snippet:

var convertedDate = new Date(dateString + new Date().getTimezoneOffset() * 60000);

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

Is it necessary to have async Javascript XMLHttpRequest automatically set the request header for XMLHttpRequest?

I recently implemented a small async GET request to my server using vanilla JavaScript. var rReq = new XMLHttpRequest(); rReq.onload = function (e) { window.updateCartnRows(e.target.response); }; rReq.open('GET', &apo ...

When it comes to deploying middleware, accessing cookies becomes more challenging. However, in a local setup, Next.js allows middleware to

I have set up a NextJS frontend application with a backend powered by NodeJS and ExpressJS. Authentication and authorization are handled using JWT token-based system, where the backend server sets the token and the frontend server validates it to grant acc ...

Attempting to extract information from an array of strings containing the URL of an API

I am looking to extract data from an array that contains APIs, but the issue is that the number of APIs in the array varies. For example, some arrays may have 3 API addresses while others have just 2. { "name": "CR90 corvette", "m ...

Authorization setup encountered an issue: an unexpected character was found at the beginning of the JSON data on line 1, column

I'm currently in the process of setting up a login page for users on my website, using mongoose, express, bcrypt, and nodejs. However, I am encountering an issue when trying to input the username and password. The error message that I receive is as fo ...

Error message encountered: "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0, specifically occurring on the get request

Upon completing the construction of my project, I have encountered an error following the building of my application. The error message reads: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 This error only appears on pages ...

Accessing a span element using an eval function

I have a function that accesses an input element and updates its value using the following line of code: eval('document.forms[0].telephone').value = $telephone[$i]; Now, I need to transfer this value to a span, but I'm having trouble refer ...

Obtaining varied outcomes while printing filtered information

As a beginner in React.js using hooks, I prefer to learn through hands-on coding. My query revolves around fetching data from a specific URL like ksngfr.com/something.txt and displaying it as shown in the provided image (I only displayed numbers 1-4, but t ...

Is it possible to run a local file on a localhost server in Sublime Text 3 with the help of the SideBar

I am attempting to host my index.html file on a localhost server in order to utilize an angular routing directive. Despite following the steps, I am encountering issues. //sidebarenchancements.json { "file:///C:/Users/Jdog/Desktop/projects/Calibre/soci ...

Enhance the user experience with a personalized video player interface

I am facing difficulty in creating a responsive video with custom controls. While I understand that using a <figure></figure> element and setting the width to 100% makes the video responsive, I am struggling with making the progress bar also r ...

Finding alternative solutions without using the find() method when working with Angular

How can I use an equivalent to find(".class") in AngularJS? I came across this solution: //find('.classname'), assumes you already have the starting elem to search from angular.element(elem.querySelector('.classname')) I attempted to ...

I am seeking guidance on retrieving the value of a text box that is activated by a radio button through jquery within the provided code

When conducting my test case, the user is presented with a choice between ielts and toefl. If the user chooses ielts, an input box appears where they can enter their ielts score. My goal is to extract and store the value entered in that input box. Check ou ...

Leveraging $pristine in AngularJS for Form Validation

My form utilizes angular validation, but I want to disable it upon page load. Below is a simplified version of my form: <form ng-submit="vm.submit()" name="form" novalidate> <input class="form-control" ng-model="vm.userName" required /> ...

Best practices for structuring npm scripts and multiple webpack configurations

My project consists of multiple dashboards, and I've decided to create separate scripts in my package.json for each one. Building all the dashboards during development when you only need to work on one can be time-consuming. So, I discovered that it&a ...

The input unexpectedly reached its limit, causing a jquery error

Encountering an error that says: Uncaught SyntaxError: Unexpected end of input on line 1. Check out the code below: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html x ...

An issue occurred while employing Promise.all: TypeError - the intermediate value is not iterable within the code

I am currently attempting to halt a series of SQL instances, and due to its asynchronous nature, I have implemented the use of Promise.all. However, I'm encountering an error in the code on: TypeError: (intermediate value) is not iterable at Prom ...

Sending a JavaScript function as part of an ajax response

I'm currently working on a system where the user can submit a form through AJAX and receive a callback in response. The process involves the server processing the form data and returning both an error message and a JavaScript function that can perform ...

Column on the far right of the grid with a frozen position

I need to design an Angular grid where the last column remains frozen. This frozen column should display the summation of all row values, and the last row should be editable. I am able to create the Angular grid itself, but I am struggling with how to stru ...

What could be the reason behind the malfunction of my jQuery .css method?

I am currently working on a taglist that allows users to add and remove tags, connected with mySQL. I have successfully retrieved the tags from the database using an ajax call, but I am unable to perform any operations on them, not even apply a basic style ...

Developing an array-based multiple choice quiz

Being a complete novice, I am currently immersed in designing a multiple-choice quiz using arrays. The questions all follow a similar template: "Which word in the following has a similar meaning to '_________'." To implement this, I have created ...

Ways to make a div disappear gradually when the user is not active, or completely remove it to reveal a different div

I'm having trouble making this work the way I want it to. I have a div element that acts as a button and I only want it to appear when the user interacts with the screen (via touch or mouse). It should stay visible for 2 seconds after inactivity and t ...