📜  以秒为单位的时刻 unix 时间 (1)

📅  最后修改于: 2023-12-03 15:06:40.907000             🧑  作者: Mango

以秒为单位的时刻 Unix 时间

简介

在计算机编程中,时间戳(timestamp)表示时间的一种方法,通常指格林威治时间1970年01月01日00时00分00秒起至现在的总秒数。这种时间表示方法被称为“Unix时间戳”或“Unix时间”。以秒为单位的时刻 Unix 时间是一个非常重要的概念,它在计算机领域中广泛应用,例如记录事件发生时间、进行时间比较等等。

时间类型

在计算机编程中,时间一般使用整数类型表示,它可以分为两种:

  1. 32 位表示的 Unix 时间戳,它可以用整形变量(int)表示;
  2. 64 位表示的 Unix 时间戳,它可以用长整形变量(long long)表示;
时间转换

Unix 时间戳可以表示一个具体的时间点(如 2021 年 8 月 1 日 0 时 0 分 0 秒),也可以表示两个时间点之间的时间差(如相隔 2 天 12 小时 30 分钟),在使用中应根据需求进行转换。

时间戳转时间

时间戳转时间一般使用 ctime() 函数,它可以将时间戳转换为一个以字符串形式表示的时间,例如:

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

int main()
{
    time_t now = 1627776000; // 2021 年 8 月 1 日 0 时 0 分 0 秒的 Unix 时间戳
    printf("%s", ctime(&now)); // 输出:Sun Aug  1 00:00:00 2021
    return 0;
}
时间转时间戳

时间转时间戳一般使用 mktime() 函数,它可以将一个以 struct tm 结构体表示的时间转换为 Unix 时间戳,例如:

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

int main()
{
    struct tm t = {0};
    t.tm_year = 121; // 2021 年 - 1900
    t.tm_mon = 7; // 8 月 - 1
    t.tm_mday = 1; // 1 日
    time_t now = mktime(&t);
    printf("%ld", now); // 输出:1627776000
    return 0;
}
时间差转时间

时间差转时间一般使用 gmtime() 函数,它可以将一个以秒为单位的时间差转换为一个以 struct tm 结构体表示的时间,例如:

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

int main()
{
    time_t t = 3600 * 24 * 2 + 3600 * 12 + 60 * 30; // 相隔 2 天 12 小时 30 分钟
    struct tm *res = gmtime(&t);
    printf("%d-%d-%d %d:%d:%d", res->tm_year + 1900, res->tm_mon + 1, res->tm_mday, res->tm_hour, res->tm_min, res->tm_sec); // 输出:1970-01-03 12:30:00
    return 0;
}
总结

以秒为单位的时刻 Unix 时间是计算机编程中的重要概念,在使用中应注意时间类型的选择以及时间的转换。以上介绍的时间转换函数只是几个简单的例子,还有许多其他的函数可以使用,读者可以根据自己的需求选择适合的方法。