Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>mktime</code> can do almost all of the work for you. To find the number of days between two dates, each specified by a <code>struct tm</code>, you could use:</p> <pre><code>int days_between (struct tm *tsa, struct tm *tsb) { time_t a = mktime(tsa); time_t b = mktime(tsb); return (b - a)/(60*60*24); } </code></pre> <p>This divides the difference in seconds by the number of seconds in a day.</p> <p>So the days of the year could be calculated like this:</p> <pre><code>int days_of_year (int y) { struct tm tsa = {0}; struct tm tsb = {0}; tsa.tm_mday = 1; tsa.tm_year = y - 1900; tsb.tm_mday = 1; tsb.tm_year = y + 1 - 1900; return days_between(&amp;tsa, &amp;tsb); } </code></pre> <p>The days of the month is similar, but you would keep the year constant, and use the next month in <code>tsb</code>.</p> <p>To calculate the number of weekdays, there are always at least 8 in the first 28 days. Then, depending on how many days there are in the month, you have to consider the remaining days. The <code>tm_wday</code> field provides the days since Sunday for the date in the <code>struct tm</code>.</p> <pre><code> int dss = tsa.tm_wday; weekdays = 8; switch (days) { case 31: if (dss == 0 || dss == 6) weekdays += 1; dss = (dss + 1) % 7; case 30: if (dss == 0 || dss == 6) weekdays += 1; dss = (dss + 1) % 7; case 29: if (dss == 0 || dss == 6) weekdays += 1; default: break; } </code></pre> <p>The complete example can be found at <a href="http://ideone.com/qQo3U" rel="nofollow">http://ideone.com/qQo3U</a></p> <p>To calculate leap year, the logic for the Gregorian Calendar is: A year is a leap year if the year is divisible by 4, except if it is also divisible by 100, in which case it is a leap year if it is divisible by 400.</p> <pre><code>int is_leap_year (int y) { return (y % 4) ? 0 : ((y % 100) ? 1 : !(y % 400)); } </code></pre> <p>However, <code>mktime</code> already knows about this, and can figure it out for you, as has already been demonstrated.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload