Turning Node.js timestamp into MySQL format

Currently, I am using Node (Express.js) to update a MySQL database with the current date. While it is functional, my code seems to be repetitive.

let newDate = new Date();
let yearNow = newDate.getFullYear();
let monthNow = newDate.getMonth();
let dayNow = newDate.getDate();
let hourNow = newDate.getHours();
let minuteNow = newDate.getMinutes();
let secondNow = newDate.getSeconds();
let timeNow = `${yearNow}-${monthNow + 1}-${dayNow} ${hourNow}:${minuteNow}:${secondNow}`;

I wonder if there is a way to achieve the same result with fewer characters?

Answer №1

To reduce unnecessary steps, consider simplifying like this:

   var currentDateTime = new Date();
   var yearNow = currentDateTime.getFullYear()
   var monthNow = currentDateTime.getMonth();
   var dayNow = currentDateTime.getDate();
   var hourNow = currentDateTime.getHours();
   var minuteNow = currentDateTime.getMinutes();
   var secondNow = currentDateTime.getSeconds();
   var fullDateTime = yearNow + '-' + (monthNow + 1) + '-' + dayNow + ' ' + hourNow + ':' + minuteNow + ':' + secondNow;

Alternatively, someone may choose to use an array to break down the parts of the date object for efficiency. However, unless you are in urgent need of speeding up your script's execution time, it may not be necessary.

It is generally advisable not to optimize code unless there is a clear benefit in terms of performance improvement. If it's not causing any issues...

On another note, you might find interest in

Answer №2

Check out moment.js

var currentTime = moment().add(1,'month').format("YYYY-MM-DD h:mm:ss A");   

Here's the jsfiddle link. If you're using nodeJS, you can include var moment = require('moment'); to use it in your code. The rest of the code remains unchanged.

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

Troubleshooting EasyTabs: Localhost Issue with Ajax Tab Configurations

I've implemented EasyTabs for organizing my tabs on a webpage. I decided to use ajax-tabs functionality in order to fetch content from other pages when users click on the navigation menu buttons. However, I've encountered an issue where the conte ...

The issue with CKEDITOR is that it fails to send data through ajax upon the initial submission

When using CKEDITOR, I am experiencing an issue where my forms do not send data to the server on the first submit. If I click the submit button once, empty fields are sent without any input from me. However, when I submit the form a second time, only then ...

The size of objects on canvas is not consistent when loading with fabric.js loadFromJSON

Click here to view the code var canvas = new fabric.Canvas('canvas_1'); var canvas2 = new fabric.Canvas('canvas_2'); var imgObj = new Image(); imgObj.src = "https://gtaprinting.ca/wp-content/uploads/2021/05/blank-t-shirt-front-gre ...

The Next.js React app is constantly loading without any interruptions

Just diving into Next.js and attempting to transform a single HTML page into a Next.js website in order to integrate sanity. Managed to import all necessary assets, but stuck with the persistent preloader issue. After inspecting elements, noticed that a fi ...

The condition is not being recognized after clicking the third button

When the button is clicked for the first time in the code snippet below, all divs except for the red one should fade out. With each subsequent click, the opacity of the next div with a higher stack order should be set to 1. Everything works fine until the ...

What could be causing my default prop to not be transmitted to the child component in vuejs2?

Having trouble passing a default value to my Leaflet map child component before fetching the desired data from an API endpoint. I tried using country coordinates like latitude and longitude, but it's not working as expected. This is how I attempted t ...

Searching Multiple Index Types in Elasticsearch: How to Perform a "More like this" Query

We have a dataset called dataIndex that contains information on two types: users and jobs. users: { tags: ['a', 'b'], locations: ['NY', 'SF'] experience: [ { title: 'Software Eng ...

Remove any objects from the array that have empty values when filtered

I am facing a challenge with filtering objects in an array. Each object contains a title and rows, where the rows also have a risk value (like P1, P2, P3, etc.). My goal is to extract only the rows that have a risk equal to P1 while skipping any objects th ...

Utilizing API routes within your React application

After creating my own API using nodejs, express and mongoDB, I successfully tested the routes with postman. However, I am struggling to integrate these routes into my react app for CRUD operations on the data. Despite having previous experience working wit ...

Sharing information between React components involves passing data as props. By sending data from

Brand new to React and still figuring things out. Here's the scenario: <div> <DropDown> </DropDown> <Panel> </Panel> </div> After selecting a value in the dropdown and storing it as currentL ...

Exploring the possibilities of web scraping using phantomJS and NodeJS

Currently, I'm working through a tutorial found at the following link: However, when I execute the code provided in the tutorial: var host = 'http://www.shoutcast.com/?action=sub&cat=Hindi#134'; var phantom = require('phantom& ...

Encountering a Problem with NPM Installation - Error Message from Node-Pre-G

Every time I attempt to run npm-install, I encounter the following error message: npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\Program Files (x86)\nodejs\node.exe" "C:\Program Files (x8 6)\nodejs\node_modules\npm&b ...

What is preventing this setTimeout from triggering?

My experience with Knockout js has left me puzzled, as I seem to be missing a key concept. Despite no error messages, it's challenging for me to pinpoint where exactly the issue lies. All I want is to periodically fetch data and update my table using ...

"Efficiently fetch data with an Express GET request without the

My goal is to send the client the HTML page (create.html) in response to a GET request triggered by a button click using fetch. I am intentionally avoiding the use of a form due to formatting and potential scalability issues. The code acknowledges that the ...

Getting the download URL generated by Firebase on a Firebase function is a common task that can

After successfully uploading an image using the Firebase SDK in Flutter, I am able to retrieve the download URL on the Flutter side by calling getDownloadUrl() on the reference. Now, my goal is to access this URL in my Cloud Function trigger so that once a ...

A guide on parsing a stringified HTML and connecting it to the DOM along with its attributes using Angular

Looking for a solution: "<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing e ...

Querying a Nested _id from the query string in MongoDB and Express

Utilizing: node/express/mongodb/mongoose After setting up the necessary components, including my schema and model, I am able to perform queries as required. However, one particular query has me stumped - how can I pass the express request.query object to ...

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...

PHP database backup scripts with encoding and escaping techniques

I have tried numerous scripts to backup my mySQL database, but they all fail. Interestingly, phpMyAdmin is the only one that properly escapes my strings. What could be causing this issue? Within some of the strings in my database, I have international cha ...

Exploring the power of V-for with checkboxes in VueJS

One issue I am facing is related to triggering my save method only when a checkbox is selected or true in Vue JS. I have no problem listing values and saving them to the database using axios, Vue JS, and Spring Boot. However, every time I click the checkbo ...