0

I'm using Node (Express.js) to update a MySQL database with the date now and it works fine but my code is a little repetitious.

var newYears = new Date();
var newMonths = new Date();
var newDays = new Date();
var newHours = new Date();
var newMinutes = new Date();
var newSeconds = new Date();
var yearNow = newYears.getFullYear();
var monthNow = newMonths.getMonth();
var dayNow = newDays.getDate();
var hourNow = newHours.getHours();
var minuteNow = newMinutes.getMinutes();
var secondNow = newSeconds.getSeconds();
var timeNow = yearNow + '-' + ( monthNow + 1 ) + '-' + dayNow + ' ' + hourNow + ':' + minuteNow + ':' + secondNow;

How few characters can the same result be achieved with?

2 Answers 2

1

You could cut out some overhead like this:

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

Alteratively someone else might set up an array splitting the component parts of the Dateobject to save a few processor cycles, but unless you find yourself desperately needing to cut down the execution time of your script, don't worry.

A good rule of thumb is if you can't quantify the speed-up, you shouldn't try to optimize for it. If it ain't broke...

On the other hand, you might like http://perlgolf.sourceforge.net/

Sign up to request clarification or add additional context in comments.

1 Comment

If you wish to format the date correctly (YYYY-MM-DD HH:MM:SS instead of YYYY-M-D H:M:S as you have now), you can do this: var timeNow = yearNow + '-' + String('00' + (monthNow + 1)).slice(-2) + '-' + String('00' + dayNow).slice(-2) + ' ' + String('00' + hourNow).slice(-2) + ':' + String('00' + minuteNow).slice(-2) + ':' + String('00' + secondNow).slice(-2)
1

Take a look at moment.js

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

Here is the jsfiddle. You can use var moment = require('moment'); if you want to use nodeJS. Rest of the code will be the same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.