1

I have this code which generates the current date + time in javascript:

    var date_variable = new Date();

    var year    = date_variable.getFullYear();
    var month   = date_variable.getMonth() + 1;
    var day     = date_variable.getDate();

    var hour    = date_variable.getHours();
    var minutes = date_variable.getMinutes();
    var seconds = date_variable.getSeconds();

    var full_date = year + month + day + hour + minutes + seconds;

    console.log(year);
    console.log(month);
    console.log(day);
    console.log(hour);
    console.log(minutes);
    console.log(seconds);
    console.log(full_date);

Everything in console displays fine, except when it comes to the full_date variable. This is what's displayed in console:

   2014
   8
   27
   10
   53
   10
   2122

My question is, why does the last output not combine my date + time into a single string?

Thanks

2
  • 1
    you're adding numbers together. So you get the sum of them. Commented Aug 27, 2014 at 2:58
  • 1
    If your project will work extensively with dates I recommend you having a look at momentjs.com Commented Aug 27, 2014 at 3:07

2 Answers 2

2

You need to concatenate the numbers with a string first.

var full_date = year +""+ month +""+ day +""+ hour +""+ minutes +""+ seconds;
Sign up to request clarification or add additional context in comments.

Comments

0

Each of the properties you are accessing return a number. When you add them together with the + operator, you are just adding numbers together.

If you substitute the variables used in full date, it would look something like:

var full_date = 2014 + 8 + 26 + . . .

All you have to do is put a strings in the expression and you will get what you want.

In all honesty though, you should use Date.toLocalDateString() or Date.toLocalTimeString() if the format works for you. You can read the documentation about them on MDN's Date reference page.

3 Comments

Oh yea, damn I forgot about that. Thanks a tone
you can do var full_date = '' + year + month + ...; The empty string will force the numbers into strings. (that's 2 single quote marks btw) Faster to type then trying to call toString on each value.
Yep, just found that answer a few min ago. Cheers for the help :)

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.