Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,890 questions

51,819 answers

573 users

How to calculate the number of weekdays between two dates in C

1 Answer

0 votes
#include <stdio.h>
#include <time.h>

int countWeekDays(struct tm d1, struct tm d2) {
    time_t time1 = mktime(&d1);
    time_t time2 = mktime(&d2);

    double ndays = 1 + difftime(time2, time1) / (60 * 60 * 24);
    int nsaturdays = (int)((ndays + d1.tm_wday) / 7);

    return (int)ndays - 2 * nsaturdays
           - (d1.tm_wday == 0 ? 1 : 0)
           + (d2.tm_wday == 6 ? 1 : 0);
}

int main() {
    struct tm d1 = {0}; // Initialize to zero
    struct tm d2 = {0};

    d1.tm_year = 2025 - 1900; d1.tm_mon = 0; d1.tm_mday = 1;  // 2025-01-01
    d2.tm_year = 2025 - 1900; d2.tm_mon = 0; d2.tm_mday = 7;  // 2025-01-07
    printf("%d\n", countWeekDays(d1, d2));

    d1.tm_year = 2025 - 1900; d1.tm_mon = 1; d1.tm_mday = 1;  // 2025-02-01
    d2.tm_year = 2025 - 1900; d2.tm_mon = 1; d2.tm_mday = 10; // 2025-02-10
    printf("%d\n", countWeekDays(d1, d2));

    d1.tm_year = 2024 - 1900; d1.tm_mon = 0; d1.tm_mday = 1;  // 2024-01-01
    d2.tm_year = 2024 - 1900; d2.tm_mon = 11; d2.tm_mday = 31; // 2024-12-31
    printf("%d\n", countWeekDays(d1, d2));

    d1.tm_year = 2025 - 1900; d1.tm_mon = 0; d1.tm_mday = 1;  // 2025-01-01
    d2.tm_year = 2025 - 1900; d2.tm_mon = 11; d2.tm_mday = 31; // 2025-12-31
    printf("%d\n", countWeekDays(d1, d2));

    return 0;
}

  
/*
run:
  
5
6
262
261
  
*//

 



answered Feb 18, 2025 by avibootz

Related questions

1 answer 64 views
1 answer 79 views
1 answer 76 views
1 answer 57 views
1 answer 71 views
1 answer 110 views
2 answers 155 views
...