Convert time structure to rawtime

I'm trying to write a program that asks the user for time input and then converts it to rawtime.

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

int main(){

    int year, month, month_day, day, hour, minute, second;

    printf("Enter the following data:\n");

    printf("Which year?: ");
    scanf("%d", &year);

    printf("Which month?: ");
    scanf("%d", &month);

    printf("Which day?: ");
    scanf("%d", &month_day);

    printf("Which hour?: ");
    scanf("%d", &hour);

    printf("Which minute?: ");
    scanf("%d", &minute);

    printf("Which second?: ");
    scanf("%d", &second);

    struct tm givenTime;
    givenTime.tm_year = year;
    givenTime.tm_mon = month;
    givenTime.tm_mday = month_day;
    givenTime.tm_hour = hour;
    givenTime.tm_min = minute;
    givenTime.tm_sec = second;

    //Now I need to convert given input to rawtime, i.e turn all the input into seconds passed since Jan 1, 1970

Upvotes: 0

Views: 437

Answers (1)

chux
chux

Reputation: 153498

Use mktime() to convert the Y-M-D H-M-S into time_t, which is usually the integer seconds since 1970, universal time.

struct tm references months since January and years since 1900. struct tm also has a member for daylight savings time. Use 0 for standard time and 1 for daylight time. Set that to -1 if you are not certain about the daylight time status of your time stamp.

Since struct tm may have other important members, best to initialize all to 0.

#include <time.h>

struct tm givenTime = { 0 };
givenTime.tm_year = year - 1900;
givenTime.tm_mon = month - 1;
givenTime.tm_mday = month_day;
givenTime.tm_hour = hour;
givenTime.tm_min = minute;
givenTime.tm_sec = second;
givenTime.tm_isdst = -1;

time_t now = mktime(&givenTime);
if (now == -1) {
  puts("Conversion failed.");
}

// Implementation dependent output
printf("time_t now %lld\n", (long long) now);

To properly determine the seconds since some epoch like Jan 1, 1970, subtract two time_t with double difftime() which always returns the difference in seconds.

// Jan 1, 1970 0:00:00 local time
struct tm epochTime = { 0 };
epochTime.tm_year = 1970 - 1900;
epochTime.tm_mon = 1 - 1;
epochTime.tm_mday = 1;
epochTime.tm_hour = 0;
epochTime.tm_min = 0;
epochTime.tm_sec = 0;
epochTime.tm_isdst = -1;
time_t time0 = mktime(&epochTime);

double dif = difftime(now , time0);
printf("dif %.0f seconds\n", dif);

Upvotes: 2

Related Questions