Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more precise than a new DateTime in a Dart web app?

Tags:

dart

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?

like image 797
Seth Ladd Avatar asked Apr 01 '13 05:04

Seth Ladd


People also ask

Which date is greater in Flutter?

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.

How do I set the time on my DateTime dart?

dart'; DateTime now = DateTime. now(); String formattedTime = DateFormat. Hms(). format(now); print(formattedTime);


2 Answers

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);
}
like image 127
Seth Ladd Avatar answered Nov 01 '22 11:11

Seth Ladd


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.

like image 40
Florian Loitsch Avatar answered Nov 01 '22 10:11

Florian Loitsch