I have a script that prints the current date and time in JavaScript, but the DATE is always 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
.getMonth()returns a zero-based number so to get the correct month you need to add 1, so calling.getMonth()in may will return4and not5.So in your code we can use
currentdate.getMonth()+1to 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 theDateobject which will return an integer representing the current day of the week (0-6)0 == Sundayetcso your code should look like this:
You can make use of the
Dateprototype object to create a new method which will return today’s date and time. These new methods or properties will be inherited by all instances of theDateobject 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 –