Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Sunday, May 27, 2012
How do you get a timestamp in JavaScript?
How can I get a timestamp in JavaScript?
Something similar to Unix's timestamp, that is, a single number that represents the current time and date. Either as a number or a string.
JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.
This will give you a Unix timestamp (in seconds):
var unix = Math.round(+new Date()/1000);
This will give you the milliseconds since the epoch (not Unix timestamp):
The following returns the number of milliseconds since the epoch.
ReplyDeletenew Date().getTime();
+new Date;
ReplyDeleteI like it, because it is small.
JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.
ReplyDeleteThis will give you a Unix timestamp (in seconds):
var unix = Math.round(+new Date()/1000);
This will give you the milliseconds since the epoch (not Unix timestamp):
var milliseconds = new Date().getTime();
var timestamp = Number(new Date()); // current time as number
ReplyDeletevar $time = Date.now || function() {
ReplyDeletereturn +new Date;
};
$time()
new Date().valueOf()// returns the number of milliseconds since the epoch
ReplyDeletetime = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);
ReplyDeleteThe Date.getTime() can be very used with a little tweak:
ReplyDeleteThe value returned by the getTime method is the number of milliseconds
since 1 January 1970 00:00:00 UTC.
To get the Unix timestamp such as the one returned by PHP time() function, divide this number by 1000, round or floor if necessary:
(new Date()).getTime() / 1000
var d=new Date();
ReplyDeletevar timestamp = new Array(2);
timestamp[1] = d.getDate();
timestamp[2] = d.getMonth();
document.write(timestamp[1]);
switch (timestamp[2])
{
case 0: document.write("Jan");
break;
case 1: document.write("Feb");
break;
case 2: document.write("Mar");
break;
case 3: document.write("Apr");
break;
case 4: document.write("May");
break;
case 5: document.write("June");
break;
case 6: document.write("July");
break;
case 7: document.write("Aug");
break;
case 8: document.write("Sept");
break;
case 9: document.write("Oct");
break;
case 10: document.write("Nov");
break;
case 11: document.write("Dec");
break;
}