首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将时间结构转换为rawtime

将时间结构转换为rawtime
EN

Stack Overflow用户
提问于 2022-03-23 23:55:30
回答 1查看 94关注 0票数 0

我正在编写一个程序,它要求用户输入时间,然后将其转换为rawtime。

代码语言:javascript
复制
#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
EN

回答 1

Stack Overflow用户

发布于 2022-03-24 01:57:15

使用mktime()将Y转换为time_t,这通常是1970年以来的整数秒.

struct tm指的是一月以来的月份和1900年以来的年份。struct tm也有一个夏时制成员。标准时间使用0,白天使用1。如果您不确定时间戳的日照时间状态,请将其设置为-1。

由于struct tm可能有其他重要成员,所以最好将所有成员初始化为0。

代码语言:javascript
复制
#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(),后者总是以秒为单位返回差值。

代码语言:javascript
复制
// 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);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71595466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档