5

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 ?

Max L.
  • 9,774
  • 15
  • 56
  • 86

1 Answers1

11

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

nemequ
  • 16,623
  • 1
  • 43
  • 62
  • Thanks! I noticed that get_monotonic_time doesn't return the number of microseconds since January 1, 1970 UTC. get_real_time returns something else, (monotinic_time returned 587731122, while real_time returned 1382202816518 when they were both run within 5 minutes) How would I get a monotonic real_time (number of microseconds since January 1, 1970 UTC) ? – Max L. Oct 19 '13 at 17:19
  • "monotonic real_time" is nonsensical. If you need real time use get_real_time. I only mentioned monotonic time because a lot of people who think they need real time would be better off using monotonic time (e.g., for measuring time between events). – nemequ Oct 19 '13 at 17:27
  • see also http://stackoverflow.com/questions/3523442/difference-between-clock-realtime-and-clock-monotonic – Jens Mühlenhoff Oct 19 '13 at 18:30