vala: is this the correct way to get the current time in milliseconds ?

StackOverflow https://stackoverflow.com/questions/19467849

  •  01-07-2022
  •  | 
  •  

Frage

Using this library with Vala :

http://valadoc.org/#!api=glib-2.0/GLib.DateTime

    GLib.DateTime now = new GLib.DateTime.now_local();

    var sec = now.to_unix()
    var msec = (sec * 1000) + now.get_microsecond();

is this the correct way to get the current time in millisecond ?

is there a better way ?

War es hilfreich?

Lösung

GLib.DateTime is a valid way of doing this, and it's a bit weird that you're requesting a local time then converting it to unix time (which implicitly converts to UTC). The real problem, though, is that you're conflating milliseconds (1/1000th of a second) and microseconds (1/1000000th of a second). So change the last line to

var msec = (sec * 1000) + (now.get_microsecond () / 1000);

Alternatively, an easier way would be to use GLib.get_real_time:

int64 msec = GLib.get_real_time () / 1000;

Depending on your use case you might want to consider using monotonic time instead of real time (see GLib.get_monotonic_time

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top