以下是用 C 语言编写的网站运行时间的代码,单位从年到秒,并且秒钟动态更新的示例:

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

int main() {
    // 获取当前时间
    time_t currentTime;
    time(&currentTime);

    // 设置网站启动时间
    struct tm startTime;
    startTime.tm_year = 122;    // 年份减去 1900,即 2022 年 - 1900 年 = 122 年
    startTime.tm_mon = 0;       // 月份从 0 开始,即 1 月为 0
    startTime.tm_mday = 1;      // 日期为 1 号
    startTime.tm_hour = 0;      // 小时为 0
    startTime.tm_min = 0;       // 分钟为 0
    startTime.tm_sec = 0;       // 秒钟为 0
    startTime.tm_isdst = -1;    // 是否为夏令时,-1 表示不确定

    // 计算当前时间与网站启动时间的差值
    time_t startTimeInSeconds = mktime(&startTime);
    time_t timeDifference = currentTime - startTimeInSeconds;

    // 将差值转换为年、天、小时、分钟和秒
    int years = timeDifference / (365 * 24 * 60 * 60);
    timeDifference = timeDifference % (365 * 24 * 60 * 60);

    int days = timeDifference / (24 * 60 * 60);
    timeDifference = timeDifference % (24 * 60 * 60);

    int hours = timeDifference / (60 * 60);
    timeDifference = timeDifference % (60 * 60);

    int minutes = timeDifference / 60;
    int seconds = timeDifference % 60;

    // 输出网站运行时间
    printf('网站已运行:%d 年, %d 天, %d 小时, %d 分钟, %d 秒\n', years, days, hours, minutes, seconds);

    // 动态更新秒钟
    while (1) {
        seconds++;
        printf('\r网站已运行:%d 年, %d 天, %d 小时, %d 分钟, %d 秒', years, days, hours, minutes, seconds);
        fflush(stdout);
        sleep(1);
    }

    return 0;
}

在上述代码中,我们首先使用 time 函数获取当前时间的时间戳。然后,我们设置网站启动时间的年、月、日、小时、分钟和秒钟,并使用 mktime 函数将其转换为时间戳。

接下来,我们计算当前时间与网站启动时间的差值,并将差值转换为年、天、小时、分钟和秒。

最后,我们使用一个无限循环来动态更新秒钟。在每次循环中,我们将秒钟递增 1,并使用 \r 将光标移动到行首,然后使用 printf 函数输出运行时间,并使用 fflush 函数刷新输出缓冲区。这样,秒钟就会动态更新。

请注意,代码中的网站启动时间需要根据实际情况进行调整和更改。此外,我们使用了 sleep 函数来使程序每隔 1 秒钟暂停,以实现秒钟的动态更新。这里需要包含 <unistd.h> 头文件以使用 sleep 函数。


原文地址: https://www.cveoy.top/t/topic/mmn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录