Am I right that g_date_copy doesn't work?

I made a new GDate with g_date_new, set it to the current date with g_date_set_time_t. This works fine, I look at the contents of the GDate in the debugger and it shows todays date.

So then I call g_date_copy and look at the returned date and its completely wrong, not even close. It might well have returned and unintialised GDate from what I can see. This is all in the same function, one directly after the other. No way for anything else to mess the process up.

Does g_date_copy not do any copying?

No, it should work.

Could you please post some minimal example code which reproduces your problem?

1 Like

Hello Philip, thanks for responding, I had changed the code since asking but I recreated to make sure I wasn’t imagining it going wrong. It’s simply this:

GDate *date = g_date_new ();
g_date_set_time_t (date, time (0));
GDate *copy = g_date_copy (date);

That was why I asked, I thought I must be doing something wrong but I couldn’t see it. After this code has run, date contains:

julian_days: 737362
julian: 1
dmy: 1
day: 30
month: 10
year: 2019

copy contains:

julian_days: 737362
julian: 1
dmy: 0
day: 21
month: 5
year: 5

Looking at it now, I can see that its copied the julian part of the date but not the DMY, so it is a valid date. I was confused by the DMY part, my mistake entirely.

It looks like you were accessing the fields of the GDate struct directly to print out those values. If you use the accessor functions (for example, g_date_get_month()) instead, then the correct values will be printed for the copy. The copy lazily calculates the DMY version of the date from the Julian value. :slight_smile:

Arguably g_date_copy() could copy this DMY information across, so what’s happening here is a little awkward, but it’s not a bug. As the documentation says, the accessor functions should be used rather than reading the GDate struct members directly.

That said, we’re generally advocating using GDateTime for things now, since it has a more modern API. GDate is still appropriate for situations where you’re only tracking dates, though, and not tracking times at all. :slight_smile:

The documentation is quite clear about not accessing the structure directly. I was looking at it in a debugger. However, it turned out the bug I was chasing was caused by something else entirely.

This has got me wondering about something else now. How would you recommend handling changes of daylight saving time? My program displays actions taken over a day, one hour at a time. The pattern of hours will be different on days where DST changes. Can I detect that through the API?

:+1:

You probably do want to use GDateTime then. See g_date_time_add_hours() and g_date_time_is_daylight_savings().

1 Like

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