How do I compare the speed of two Javascript functions? - javascript

I have some Javascript that is reading in some XML. There is an older function which was used to create a JSON object from that data, and I've written a new function that I hope will create that JSON object faster.
What is the easiest and best way to determine which function is performing faster? It's a decent amount of data, so it's somewhat important to know.
Thanks.

You could use console.time("ID"); and console.timeEnd("ID"); (info here), and look the results in the Chrome Developer Tools or Firebug like so:
console.time("oldFunc");
//oldfunc();
console.timeEnd("oldFunc");
console.time("newfunc");
//newfunc();
console.timeEnd("newfunc");
Also, you could use jsperf

Some info on this and code sample here
var startDate = new Date();
// execute your tasks here
var endDate = new Date();
var timeTaken = endDate.getTime() - startDate.getTime();
alert('Time take to execute the script is '+timeTaken+' milliseconds');

(new Date).getTime();
This is how you get current time in milliseconds. Do that before and after execution of code, subtract and you have execution time in miliseconds.
Sample:
var start=(new Date).getTime();
//call your code
alert('Code took '+((new Date).getTime()-start)+'ms');
If your code organisation allows, you can make your call in a for loop, repeating n (let's say 1000) times and divide the time by n at the end.
This way you get the average speed, which is especially helpful if you function varies a lot (like network calls).

I like John Resigs way of testing the performance of a function:
function runTest(name, test, next){
var runs = [], r = 0;
setTimeout(function(){
var start = Date.now(), diff = 0;
for ( var n = 0; diff < 1000; n++ ) {
test();
diff = Date.now() - start;
}
runs.push( n );
if ( r++ < 4 )
setTimeout( arguments.callee, 0 );
else {
done(name, runs);
if ( next )
setTimeout( next, 0 );
}
}, 0);
}

Is this in the browser or server-side?
If it's server-side, I'd recommend using your shell scripting tool of choice to do the benchmarking (linux has time, windows has...whatever windows has).
If it's in the browser, then you can always wrap a certain number of iterations (10,000 is usually enough) in:
var start = new Date.getTime();
var runs = 10000;
while (runs) {
// do stuff here
runs--;
}
console.log('Finished in ' + (new Date.getTime() - start) + ' ms.');

var d1 = new Date();
function1();
var d2 = new Date();
console.log("Function 1 : ", d2.getTime() - d1.getTime());
function2();
var d3 = new Date();
console.log("Function 2 : ", d3.getTime() - d2.getTime());

Related

Script to run function at specific time with milliseconds

I have that code at below, how can I run it at 21:36:00:500 (500 is milliseconds) ?
var now = new Date();
var millisTill1 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 45, 30, 500) - now;
if (millisTill1 < 0) {
millisTill1 += 86400000;
}
setTimeout(function() {
check()
}, millisTill1);
I have tested this code for 1 minute timer execution it works. Also it just adds to the time limit after which it executes once. Kindly consider this code.
tDate = new Date();
tDate.setHours(21);
tDate.setMinutes(36);
tDate.setSeconds(0);
tDate.setMilliseconds(500);
tMillis = tDate - new Date();
if (tMillis < 0)
tMillis = tMillis + 24 * 60 * 60 * 1000; // if time is greater than 21:36:00:500 just add 24 hours as it will execute next day
setTimeout(function() {
console.log('Execute');
}, tMillis)
You can validate the code by using 1 minute ahead timer to confirm the output.
You can't do it with setTimeout. setTimeout function requires you to pass a second parameter (called millisTill1 in your example) in milliseconds.
Most browsers, have a bottom threshold of 10ms, which means you can't go below 10000 microseconds or 0.01s.
While JS is not suitable for this, most common task that would get you where you need to go would most probably use setInterval and look like:
(setInterval(function() {
var currentTime = new Date();
if (
currentTime.getHours() === 1 &&
currentTime.getMinutes() === 38 &&
currentTime.getSeconds() === 0 &&
currentTime.getMilliseconds() === 500
) {
// your code
}
}, 500))();
This one would check the time each time a pollingTime interval passes. Most commonly this would be 1 minute (60000). You can go lower, but risk performance issues. Don't forget javascript runs on the client. If you would use setTimeout time would be checked only once and your script would stop.
If you need to execute something, better use a combination of system scheduler like Task Scheduler on Windows or Automator on OSX with a scripting language like bash or python.

Javascript: date obj-date obj

As example. I want to check if time at t1 to now is more than 10s. How can I check it in angular js. I get now then substract t1. It return a number. How to convert it to second
I like to use moment.js for my Date object. It is a high level library, framework-orgnistic, and match very well with angular template system using angular-moment.
In your case you just should do it like this :
var t1 = moment();
... wait 10 sec ...
if (t1.fromNow('s') >= 10) {
...
}
It make is very easy to maintain in time, BUT cost some ressources if used to much.
Pure Javascript solution:
function checkAgo(t1, agoSecs) {
var timeAgo = new Date((new Date()).valueOf() - 1000 * agoSecs);
return t1 < timeAgo;
}
Call the function this way: checkAgo(t1, 10).

In JavaScript, how can I have a function run at a specific time?

I have a website that hosts a dashboard: I can edit the JavaScript on the page and I currently have it refreshing every five seconds.
I am trying to now get a window.print() to run every day at 8 AM.
How could I do this?
JavaScript is not the tool for this. If you want something to run at a specific time every day, you're almost certainly looking for something that runs locally, like python or applescript.
However, let's consider for a moment that JavaScript is your only option. There are a few ways that you could do this, but I'll give you the simplest.
First, you'll have to to create a new Date() and set a checking interval to see whether the hour is 8 (for 8 AM).
This will check every minute (60000 milliseconds) to see if it is eight o'clock:
window.setInterval(function(){ // Set interval for checking
var date = new Date(); // Create a Date object to find out what time it is
if(date.getHours() === 8 && date.getMinutes() === 0){ // Check the time
// Do stuff
}
}, 60000); // Repeat every 60000 milliseconds (1 minute)
It won't execute at exactly 8 o'clock (unless you start running this right on the minute) because it is checking once per minute. You could decrease the interval as much as you'd like to increase the accuracy of the check, but this is overkill as it is: it will check every minute of every hour of every day to see whether it is 8 o'clock.
The intensity of the checking is due to the nature of JavaScript: there are much better languages and frameworks for this sort of thing. Because JavaScript runs on webpages as you load them, it is not meant to handle long-lasting, extended tasks.
Also realize that this requires the webpage that it is being executed on to be open. That is, you can't have a scheduled action occur every day at 8 AM if the page isn't open doing the counting and checking every minute.
You say that you are already refreshing the page every five seconds: if that's true, you don't need the timer at all. Just check every time you refresh the page:
var date = new Date(); // Create Date object for a reference point
if(date.getHours() === 8 && date.getMinutes() === 0 && date.getSeconds() < 10){ // Check the time like above
// Do stuff
}
With this, you also have to check the seconds because you're refreshing every five seconds, so you would get duplicate tasks.
With that said, you might want to do something like this or write an Automator workflow for scheduled tasks on OS X.
If you need something more platform-agnostic, I'd seriously consider taking a look at Python or Bash.
As an update, JavaScript for Automation was introduced with OS X Yosemite, and it seems to offer a viable way to use JavaScript for this sort of thing (although obviously you're not using it in the same context; Apple is just giving you an interface for using another scripting language locally).
If you're on OS X and really want to use JavaScript, I think this is the way to go.
The release notes linked to above appear to be the only existing documentation as of this writing (which is ~2 months after Yosemite's release to the public), but they're worth a read. You can also take a look at the javascript-automation tag for some examples.
I've also found the JXA Cookbook extremely helpful.
You might have to tweak this approach a bit to adjust for your particular situation, but I'll give a general overview.
Create a blank Application in Automator.
Open Automator.app (it should be in your Applications directory) and create a new document.
From the dialog, choose "Application."
Add a JavaScript action.
The next step is to actually add the JavaScript that will be executed. To do that, start by adding a "Run JavaScript" action from the sidebar to the workflow.
Write the JavaScript.
This is where you'll have to know what you want to do before proceeding. From what you've provided, I'm assuming you want to execute window.print() on a page loaded in Safari. You can do that (or, more generally, execute arbitrary JS in a Safari tab) with this:
var safari = Application('Safari');
safari.doJavaScript('window.print();', { in: safari.windows[0].currentTab });
You might have to adjust which of the windows you're accessing depending on your setup.
Save the Application.
Save (File -> Save or ⌘+S) the file as an Application in a location you can find (or iCloud).
Schedule it to run.
Open Calendar (or iCal).
Create a new event and give it an identifiable name; then, set the time to your desired run time (8:00 AM in this case).
Set the event to repeat daily (or weekly, monthly, etc. – however often you'd like it to run).
Set the alert (or alarm, depending on your version) to custom.
Choose "Open file" and select the Application file that you saved.
Choose "At time of event" for the alert timing option.
That's it! The JavaScript code that you wrote in the Application file will run every time that event is set to run. You should be able to go back to your file in Automator and modify the code if needed.
function every8am (yourcode) {
var now = new Date(),
start,
wait;
if (now.getHours() < 7) {
start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0);
} else {
start = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 8, 0, 0, 0);
}
wait = start.getTime() - now.getTime();
if(wait <= 0) { //If missed 8am before going into the setTimeout
console.log('Oops, missed the hour');
every8am(yourcode); //Retry
} else {
setTimeout(function () { //Wait 8am
setInterval(function () {
yourcode();
}, 86400000); //Every day
},wait);
}
}
To use it:
var yourcode = function () {
console.log('This will print evryday at 8am');
};
every8am(yourcode);
Basically, get the timestamp of now, the timestamp of today 8am if run in time, or tomorrow 8am, then set a interval of 24h to run the code everyday. You can easily change the hour it will run by setting the variable start at a different timestamp.
I don t know how it will be useful to do that thought, as other pointed out, you ll need to have the page open all day long to see that happen...
Also, since you are refreshing every 5 seconds:
function at8am (yourcode) {
var now = new Date(),
start = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 8, 0, 0, 0);
if (now.getTime() >= start.getTime() - 2500 && now.getTime() < start.getTime() + 2500) {
yourcode();
}
}
Run it the same way as every8am, it look if 8am is 2.5second ahead or behind, and run if it does.
I try to give my answer hoping it could help:
function startJobAt(hh, mm, code) {
var interval = 0;
var today = new Date();
var todayHH = today.getHours();
var todayMM = today.getMinutes();
if ((todayHH > hh) || (todayHH == hh && todayMM > mm)) {
var midnight = new Date();
midnight.setHours(24,0,0,0);
interval = midnight.getTime() - today.getTime() +
(hh * 60 * 60 * 1000) + (mm * 60 * 1000);
} else {
interval = (hh - todayHH) * 60 * 60 * 1000 + (mm - todayMM) * 60 * 1000;
}
return setTimeout(code, interval);
}
With the startJobAt you can execute only one the task you wish, but if you need to rerun your task It's up to you to recall startJobAt.
bye
Ps
If you need an automatic print operation, with no dialog box, consider to use http://jsprintsetup.mozdev.org/reference.html plugin for mozilla or other plugin for other bowsers.
I will suggest to do it in Web Worker concept, because it is independent of other scripts and runs without affecting the performance of the page.
Create a web worker (demo_worker.js)
var i = 0;
var date = new Date();
var counter = 10;
var myFunction = function(){
i = i + 1;
clearInterval(interval);
if(date.getHours() === 8 && date.getMinutes() === 0) {
counter = 26280000;
postMessage("hello"+i);
}
interval = setInterval(myFunction, counter);
}
var interval = setInterval(myFunction, counter);
Use the web worker in Ur code as follows.
var w;
function startWorker() {
if (typeof(Worker) !== "undefined") {
if (typeof(w) == "undefined") {
w = new Worker("demo_worker.js");
w.onmessage = function(event) {
window.print();
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support HTML5 Web Workers";
}
}
}
I think it will help you.
I have written function which
allows expressing delay in seconds, new Date() format and string's new Date format
allows cancelling timer
Here is code:
"use strict"
/**
This function postpones execution until given time.
#delay might be number or string or `Date` object. If number, then it delay expressed in seconds; if string, then it is parsed with new Date() syntax. Example:
scheduleAt(60, function() {console.log("executed"); }
scheduleAt("Aug 27 2014 16:00:00", function() {console.log("executed"); }
scheduleAt("Aug 27 2014 16:00:00 UTC", function() {console.log("executed"); }
#code function to be executed
#context #optional `this` in function `code` will evaluate to this object; by default it is `window` object; example:
scheduleAt(1, function(console.log(this.a);}, {a: 42})
#return function which can cancel timer. Example:
var cancel=scheduleAt(60, function(console.log("executed.");});
cancel();
will never print to the console.
*/
function scheduleAt(delay, code, context) {
//create this object only once for this function
scheduleAt.conv = scheduleAt.conv || {
'number': function numberInSecsToUnixTs(delay) {
return (new Date().getTime() / 1000) + delay;
},
'string': function dateTimeStrToUnixTs(datetime) {
return new Date(datetime).getTime() / 1000;
},
'object': function dateToUnixTs(date) {
return date.getTime() / 1000;
}
};
var delayInSec = scheduleAt.conv[typeof delay](delay) - (new Date().getTime() / 1000);
if (delayInSec < 0) throw "Cannot execute in past";
if (debug) console.log('executing in', delayInSec, new Date(new Date().getTime() + delayInSec * 1000))
var id = setTimeout(
code,
delayInSec * 1000
);
//preserve as a private function variable setTimeout's id
return (function(id) {
return function() {
clearTimeout(id);
}
})(id);
}
Use this as follows:
scheduleAt(2, function() {
console.log("Hello, this function was delayed 2s.");
});
scheduleAt(
new Date().toString().replace(/:\d{2} /, ':59 '),
function() {
console.log("Hello, this function was executed (almost) at the end of the minute.")
}
);
scheduleAt(new Date(Date.UTC(2014, 9, 31)), function() {
console.log('Saying in UTC time zone, we are just celebrating Helloween!');
})
setInterval(() => {
let t = `${new Date().getHours() > 12 ? new Date().getHours() - 12 : new Date().getHours()}:${new Date().getMinutes().length < 2 ? '0' + new Date().getMinutes() : new Date().getMinutes()}:${new Date().getSeconds().length < 2 ? '0' + new Date().getSeconds() : new Date().getSeconds()} ${new Date().getHours()>12?"pm":"am"}`
console.log(t);
}, 1000);

How do I compare dates in Javascript?

I have the following situation:
I have a certain function that runs a loop and does stuff, and error conditions may make it exit that loop.
I want to be able to check whether the loop is still running or not.
For this, i'm doing, for each loop run:
LastTimeIDidTheLoop = new Date();
And in another function, which runs through SetInterval every 30 seconds, I want to do basically this:
if (LastTimeIDidTheLoop is more than 30 seconds ago) {
alert("oops");
}
How do I do this?
Thanks!
JS date objects store milliseconds internally, subtracting them from each other works as expected:
var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000;
if (diffSeconds > 30)
{
// ...
}
what about:
newDate = new Date()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
alert("oops");
}
You can do like this:
var dateDiff = function(fromdate, todate) {
var diff = todate - fromdate;
return Math.floor(diff/1000);
}
then:
if (dateDiff(fromdate, todate) > 30){
alert("oops");
}
Create a date object and use setSeconds().
controlDate = new Date();
controlDate.setSeconds(controlDate.getSeconds() + 30);
if (LastTimeIDidTheLoop > controlDate) {
...

How do I get a timestamp in JavaScript?

I want a single number that represents the current date and time, like a Unix timestamp.
Timestamp in milliseconds
To get the number of milliseconds since Unix epoch, call Date.now:
Date.now()
Alternatively, use the unary operator + to call Date.prototype.valueOf:
+ new Date()
Alternatively, call valueOf directly:
new Date().valueOf()
To support IE8 and earlier (see compatibility table), create a shim for Date.now:
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
Alternatively, call getTime directly:
new Date().getTime()
Timestamp in seconds
To get the number of seconds since Unix epoch, i.e. Unix timestamp:
Math.floor(Date.now() / 1000)
Alternatively, using bitwise-or to floor is slightly faster, but also less readable and may break in the future (see explanations 1, 2):
Date.now() / 1000 | 0
Timestamp in milliseconds (higher resolution)
Use performance.now:
var isPerformanceSupported = (
window.performance &&
window.performance.now &&
window.performance.timing &&
window.performance.timing.navigationStart
);
var timeStampInMs = (
isPerformanceSupported ?
window.performance.now() +
window.performance.timing.navigationStart :
Date.now()
);
console.log(timeStampInMs, Date.now());
I like this, because it is small:
+new Date
I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better:
Date.now()
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):
var milliseconds = new Date().getTime();
I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear
Quick and dirty solution:
Date.now() /1000 |0
Warning: it might break in 2038 and return negative numbers if you do the |0 magic. Use Math.floor() instead by that time
Math.floor() solution:
Math.floor(Date.now() /1000);
Some nerdy alternative by Derek 朕會功夫 taken from the comments below this answer:
new Date/1e3|0
Polyfill to get Date.now() working:
To get it working in IE you could do this (Polyfill from MDN):
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
If you do not care about the year / day of week / daylight saving time you need to remember this for dates after 2038:
Bitwise operations will cause usage of 32 Bit Integers instead of 64 Bit Floating Point.
You will need to properly use it as:
Math.floor(Date.now() / 1000)
If you just want to know the relative time from the point of when the code was run through first you could use something like this:
const relativeTime = (() => {
const start = Date.now();
return () => Date.now() - start;
})();
In case you are using jQuery you could use $.now() as described in jQuery's Docs which makes the polyfill obsolete since $.now() internally does the same thing: (new Date).getTime()
If you are just happy about jQuery's version, consider upvoting this answer since I did not find it myself.
Now a tiny explaination of what |0 does:
By providing |, you tell the interpreter to do a binary OR operation.
Bit operations require absolute numbers which turns the decimal result from Date.now() / 1000 into an integer.
During that conversion, decimals are removed, resulting in a similar result to what using Math.floor() would output.
Be warned though: it will convert a 64 bit double to a 32 bit integer.
This will result in information loss when dealing with huge numbers.
Timestamps will break after 2038 due to 32 bit integer overflow unless Javascript moves to 64 Bit Integers in Strict Mode.
For further information about Date.now follow this link: Date.now() # MDN
var time = Date.now || function() {
return +new Date;
};
time();
var timestamp = Number(new Date()); // current time as number
In addition to the other options, if you want a dateformat ISO, you can get it directly
console.log(new Date().toISOString());
jQuery provides its own method to get the timestamp:
var timestamp = $.now();
(besides it just implements (new Date).getTime() expression)
REF: http://api.jquery.com/jQuery.now/
Date, a native object in JavaScript is the way we get all data about time.
Just be careful in JavaScript the timestamp depends on the client computer set, so it's not 100% accurate timestamp. To get the best result, you need to get the timestamp from the server-side.
Anyway, my preferred way is using vanilla. This is a common way of doing it in JavaScript:
Date.now(); //return 1495255666921
In MDN it's mentioned as below:
The Date.now() method returns the number of milliseconds elapsed since
1 January 1970 00:00:00 UTC.
Because now() is a static method of Date, you always use it as Date.now().
If you using a version below ES5, Date.now(); not works and you need to use:
new Date().getTime();
console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch
Performance
Today - 2020.04.23 I perform tests for chosen solutions. I tested on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0
Conclusions
Solution Date.now() (E) is fastest on Chrome and Safari and second fast on Firefox and this is probably best choice for fast cross-browser solution
Solution performance.now() (G), what is surprising, is more than 100x faster than other solutions on Firefox but slowest on Chrome
Solutions C,D,F are quite slow on all browsers
Details
Results for chrome
You can perform test on your machine HERE
Code used in tests is presented in below snippet
function A() {
return new Date().getTime();
}
function B() {
return new Date().valueOf();
}
function C() {
return +new Date();
}
function D() {
return new Date()*1;
}
function E() {
return Date.now();
}
function F() {
return Number(new Date());
}
function G() {
// this solution returns time counted from loading the page.
// (and on Chrome it gives better precission)
return performance.now();
}
// TEST
log = (n,f) => console.log(`${n} : ${f()}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
This snippet only presents code used in external benchmark
Just to add up, here's a function to return a timestamp string in Javascript.
Example: 15:06:38 PM
function displayTime() {
var str = "";
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
One I haven't seen yet
Math.floor(Date.now() / 1000); // current time in seconds
Another one I haven't seen yet is
var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();
The Date.getTime() method can be used with a little tweak:
The value returned by the getTime method is the number of milliseconds
since 1 January 1970 00:00:00 UTC.
Divide the result by 1000 to get the Unix timestamp, floor if necessary:
(new Date).getTime() / 1000
The Date.valueOf() method is functionally equivalent to Date.getTime(), which makes it possible to use arithmetic operators on date object to achieve identical results. In my opinion, this approach affects readability.
The code Math.floor(new Date().getTime() / 1000) can be shortened to new Date / 1E3 | 0.
Consider to skip direct getTime() invocation and use | 0 as a replacement for Math.floor() function.
It's also good to remember 1E3 is a shorter equivalent for 1000 (uppercase E is preferred than lowercase to indicate 1E3 as a constant).
As a result you get the following:
var ts = new Date / 1E3 | 0;
console.log(ts);
I highly recommend using moment.js. To get the number of milliseconds since UNIX epoch, do
moment().valueOf()
To get the number of seconds since UNIX epoch, do
moment().unix()
You can also convert times like so:
moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()
I do that all the time. No pun intended.
To use moment.js in the browser:
<script src="moment.js"></script>
<script>
moment().valueOf();
</script>
For more details, including other ways of installing and using MomentJS, see their docs
For a timestamp with microsecond resolution, there's performance.now:
function time() {
return performance.now() + performance.timing.navigationStart;
}
This could for example yield 1436140826653.139, while Date.now only gives 1436140826653.
Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
You can only use
var timestamp = new Date().getTime();
console.log(timestamp);
to get the current timestamp. No need to do anything extra.
// The Current Unix Timestamp
// 1443534720 seconds since Jan 01 1970. (UTC)
// seconds
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720
console.log(Math.floor(Date.now() / 1000)); // 1443534720
console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720
// milliseconds
console.log(Math.floor(new Date().valueOf())); // 1443534720087
console.log(Math.floor(Date.now())); // 1443534720087
console.log(Math.floor(new Date().getTime())); // 1443534720087
// jQuery
// seconds
console.log(Math.floor($.now() / 1000)); // 1443534720
// milliseconds
console.log($.now()); // 1443534720087
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If it is for logging purposes, you can use ISOString
new Date().toISOString()
"2019-05-18T20:02:36.694Z"
Any browsers not supported Date.now, you can use this for get current date time:
currentTime = Date.now() || +new Date()
This seems to work.
console.log(clock.now);
// returns 1444356078076
console.log(clock.format(clock.now));
//returns 10/8/2015 21:02:16
console.log(clock.format(clock.now + clock.add(10, 'minutes')));
//returns 10/8/2015 21:08:18
var clock = {
now:Date.now(),
add:function (qty, units) {
switch(units.toLowerCase()) {
case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;
case 'days' : val = qty * 1000 * 60 * 60 * 24; break;
case 'hours' : val = qty * 1000 * 60 * 60; break;
case 'minutes' : val = qty * 1000 * 60; break;
case 'seconds' : val = qty * 1000; break;
default : val = undefined; break;
}
return val;
},
format:function (timestamp){
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
// Will display time in xx/xx/xxxx 00:00:00 format
return formattedTime = month + '/' +
day + '/' +
year + ' ' +
hours + ':' +
minutes.substr(-2) +
':' + seconds.substr(-2);
}
};
This one has a solution : which converts unixtime stamp to tim in js try this
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
I learned a really cool way of converting a given Date object to a Unix timestamp from the source code of JQuery Cookie the other day.
Here's an example:
var date = new Date();
var timestamp = +date;
If want a basic way to generate a timestamp in Node.js this works well.
var time = process.hrtime();
var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );
Our team is using this to bust cache in a localhost environment. The output is /dist/css/global.css?v=245521377 where 245521377 is the timestamp generated by hrtime().
Hopefully this helps, the methods above can work as well but I found this to be the simplest approach for our needs in Node.js.
For lodash and underscore users, use _.now.
var timestamp = _.now(); // in milliseconds
Moment.js can abstract away a lot of the pain in dealing with Javascript Dates.
See: http://momentjs.com/docs/#/displaying/unix-timestamp/
moment().unix();
As of writing this, the top answer is 9 years old, and a lot has changed since then - not least, we have near universal support for a non-hacky solution:
Date.now()
If you want to be absolutely certain that this won't break in some ancient (pre ie9) browser, you can put it behind a check, like so:
const currentTimestamp = (!Date.now ? +new Date() : Date.now());
This will return the milliseconds since epoch time, of course, not seconds.
MDN Documentation on Date.now
more simpler way:
var timeStamp=event.timestamp || new Date().getTime();

Categories