w3resource

C Exercises: Compute the number of seconds passed since the beginning of the month


2. Seconds Since Month Start

Write a program in C to compute the number of seconds passed since the beginning of the month.

Sample Solution:

C Code:

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

int main(void) {
    time_t now; // Variable to hold the current time
    time(&now); // Get the current time

    struct tm beg_month; // Structure to hold the beginning of the month's date and time
    beg_month = *localtime(&now); // Retrieve local time
    beg_month.tm_hour = 0; // Set hours to 0
    beg_month.tm_min = 0; // Set minutes to 0
    beg_month.tm_sec = 0; // Set seconds to 0
    beg_month.tm_mday = 1; // Set day to 1 (beginning of the month)

    double seconds = difftime(now, mktime(&beg_month)); // Calculate the difference between the current time and the beginning of the month
    printf("\n %.f seconds passed since the beginning of the month.\n\n", seconds); // Print the seconds elapsed since the beginning of the month
    return 0;
}

Output:

 222084 seconds passed since the beginning of the month.

N.B.: The result may varry for your current system date and time.

Flowchart:

Flowchart: Compute the number of seconds passed since the beginning of the month


For more Practice: Solve these Related Problems:

  • Write a C program to calculate and display the total number of seconds that have elapsed since the beginning of the current month.
  • Write a C program to compute the seconds passed since the start of the month and also display what percentage of the month has elapsed.
  • Write a C program to convert the seconds elapsed since the month’s start into days, hours, minutes, and seconds, and print the result.
  • Write a C program to calculate the seconds passed since the beginning of the month in both local time and UTC, then compare the two.

Go to:


PREV : Current DateTime Print.
NEXT : time_t to Textual Representation.

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.