Getting a new DateTime
isn't accurate enough for me. A date object in the browser gives me milliseconds as an integer. I'd like to be able to get a time that's more precise than the standard date object. Is this possible? How can I do this?
Simply use the methods isAfter() , isBefore() or isAtSameMomentAs() from DateTime . Other alternative, use compareTo(DateTime other) , as in the docs: Compares this DateTime object to [other], returning zero if the values are equal.
dart'; DateTime now = DateTime. now(); String formattedTime = DateFormat. Hms(). format(now); print(formattedTime);
Use window.performance.now()
to get a monotonic, high-resolution time. The now()
function returns a double with microseconds in the fractional.
Here is an example:
import 'dart:html';
main() {
var time = window.performance.now();
print(time); // 12123.24341221
}
Notice that now()
is not the typical "time from the epoch". Instead, it is a delta from window.performance.timing.navigationStart
.
The navigationStart
field is defined as (from the spec):
This attribute must return the time immediately after the user agent finishes prompting to unload the previous document. If there is no previous document, this attribute must return the same value as fetchStart.
The window.performance.now()
timestamp is great because it's not affected by clock skew and is more accurate than getting a new DateTime
.
If your application is driven by requestAnimationFrame
(and if not, why not? :) then you already have a high resolution timestamp!
The Future returned by animationFrame
completes with a high resolution timestamp:
Future<num> animationFrame;
You can use it like this:
gameLoop(num highResolutionTime) {
// stuff
window.animationFrame.then(gameLoop);
}
main() {
window.animationFrame.then(gameLoop);
}
If you want to measure time spans use the Stopwatch
class. It works universally (on the client and server) and should provide the best possible resolution.
var sw = new Stopwatch()..start();
doSomething();
print(sw.elapsed);
print(sw.elapsedMicroseconds);
Currently (as of April 2013) the Stopwatch in the browser doesn't yet use the window.performance
functionality, but that's a bug and should be fixed. In the meantime you can use the workaround that was suggested by Seth.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With