I have a script that prints the current date and time in JavaScript, but the DATE
is allways wrong. Here is the code:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/"+currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
It should print 18/04/2012 15:07:33
and prints 3/3/2012 15:07:33
Any help? Thanks
I have found the simplest way to get current date and time in JavaScript from here - How to get current Date and Time using JavaScript
This question is quite old and the answers are too. Instead of those monstrous functions, we now can use moment.js to get the current date, which actually makes it very easy. All that has to be done is including moment.js in our project and get a well formated date, for example, by:
I think that makes it way easier to handle dates in javascript.
My well intended answer is to use this tiny bit of JS: https://github.com/rhroyston/clock-js
When calling
.getMonth()
you need to add +1 to display the correct month. Javascript count always starts at 0 (look here to check why), so calling.getMonth()
in may will return4
and not5
.So in your code we can use
currentdate.getMonth()+1
to output the correct value. In addition:.getDate()
returns the day of the month <- this is the one you want.getDay()
is a separate method of theDate
object which will return an integer representing the current day of the week (0-6)0 == Sunday
etcso your code should look like this:
You can make use of the prototype constructor for the
Date
object and create a new method of theDate
object to return today's date and time. These new methods or properties will be inherited by all instances of theDate
object thus making it especially useful if you need to re-use this functionality.You can then simply retrieve the date and time by doing the following:
Or call the method inline so it would simply be -
.getDay returns day of week. You need .getDate instead. .getMonth returns values from 0 to 11. You'll need to add 1 to the result to get "human" month number.
Basic JS (good to learn): we use the Date() function and do all that we need to show the date and day in our custom format.
Node JS (quick & easy): Install the npm pagckage using (npm install date-and-time), then run the below.