How to get local time in microseconds in c

i want to get the local time in micro seconds using the g_get_real_time () function however as i understand it returns the time from zero time zone. How do I get local time in microseconds using glib functions?

1 Like

You can use g_date_time_new_now_local() as GDateTime provides microsecond resolution.


I thought about this function, but did not find a way to get milliseconds from the structure of GDateTime, do you know where you can find man by the structure of GDateTime?

The contents of GDateTime are private.

You can get the various components of the date and time, and then compute the microseconds:

msec = year × msecs_in_a_year
     + day_of_year × msecs_in_a_day
     + hour × msecs_in_an_hour
     + minutes × msecs_in_a_minute
     + seconds × 1000
     + microseconds / 1000

Or you could get the Unix time in seconds relative to UTC, then add the timezone’s offset in seconds, then multiply by 1_000_000, add the microseconds, and divide by 1_000.

In general, though, I have doubts as to what you’re trying to achieve. Why do you think you need time in microseconds from the local time? That kind of precision is rarely warranted, and if you’re doing comparisons it’s better to do them from a standard point in time like UTC.

1 Like

I use this time to sort records in the database, I used standard functions and structures of the с language but I’m afraid it won’t be cross-platform, so I decided to find the time using the glib functions, thank you

If you want to sort records in a database, store the date and time using a string encoding them in ISO 8601 format; then convert them to GDateTime relative to UTC, so you can compare them appropriately, taking into account the time zone.

this is a good idea thank you, but if I understand everything correctly, the database will not be able to sort the data itself because it is in ISO 8601 format

I’m fairly sure many databases have date/time sorting methods for various date formats—and if they don’t, you can sort the results yourself after performing a query.

thank you, I understood you

I solved the problem with time zones differently, I store in the database the time in milliseconds of zero utc because of this there are no problems for sorting, then when I send the data to another time zone I sort them and then add the time difference between the time zones to me it seems to be the best option

If you look at the docs for GDateTime, you’ll find g_date_time_get_microsecond() in there, and the rest of the date/time components as well (hour, minute, seconds, etc.).

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.