我正在编写一个程序,它要求用户输入时间,然后将其转换为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发布于 2022-03-24 01:57:15
使用mktime()将Y转换为time_t,这通常是1970年以来的整数秒.
struct tm指的是一月以来的月份和1900年以来的年份。struct tm也有一个夏时制成员。标准时间使用0,白天使用1。如果您不确定时间戳的日照时间状态,请将其设置为-1。
由于struct tm可能有其他重要成员,所以最好将所有成员初始化为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);若要正确确定自1970年1月1日这样的某个时期以来的秒数,请用time_t减去两个double difftime(),后者总是以秒为单位返回差值。
// 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);https://stackoverflow.com/questions/71595466
复制相似问题