0

I want to get the date and time in the following format:

yyyy.mm.dd.hh.mm.ss | 2014.11.6.20.31.24

However, my code (based on Get Current Time) is instead providing these values:

y??.m?.d?.hh.mm.ss | 114.10.4.20.31.24

Here is my code:

var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getYear() + "." + dt.getMonth() + "." + dt.getDay();
alert(date + "." + time);

Can someone please let me know why these odd values are in there 114.10.4 and how to change them to be what I want?

Community
  • 1
  • 1
Joseph
  • 3,749
  • 9
  • 28
  • 46
  • possible duplicate of [How to get current date in JavaScript?](http://stackoverflow.com/questions/1531093/how-to-get-current-date-in-javascript) – Ivan Chernykh Nov 06 '14 at 12:43

5 Answers5

2

That is because you need to use

var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + (dt.getMonth()+1) + "." + dt.getDate();
alert(date + "." + time);

If, for some weird reason, you are going only for firefox, you can use

var d = new Date(),
    formatted = d.toLocaleFormat('%Y.%m.%d.%H.%M.%S');

alert(formatted);

Finally, you can use the great moment.js library and do

var formatted = moment().format('YYYY.MM.DD.HH.mm.ss');
Gabriele Petrioli
  • 173,972
  • 30
  • 239
  • 291
1

You are using the wrong getters. Use getFullYear() instead of getYear(), and getDate() instead of getDay(). And add 1 to the month, because it starts at 0.

var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + (dt.getMonth() + 1) + "." + dt.getDate();
alert(date + "." + time);
forgivenson
  • 4,234
  • 2
  • 16
  • 28
0

Just make sure that you are using methods what you want to use e.g:

dt.getYear() => dt.getFullYear()

For further reference see this.

Vladimirs
  • 7,364
  • 4
  • 37
  • 68
0

should use getFullYear() instead of getYear() and getMonth() + 1 instead of getMonth() because it calculate form 0..11 and info about getDay()

var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + dt.getMonth() + 1 + "." + dt.getDate();
alert(date + "." + time);

dt.getDay() this day of the week

Alex Filatov
  • 2,084
  • 3
  • 30
  • 32
0

The getDay() method returns the day of the week (from 0 to 6)

You need to use getDate() to know the number of the day (from 1 to 31)

Also, you need to add 1 to getMonth() because months in JavaScript starts on 0

oscarvady
  • 440
  • 1
  • 4
  • 12