将时间/日期转换为纪元(自 1970 年以来的秒数)

发布于 2024-11-09 14:51:17 字数 724 浏览 0 评论 0原文

我正在尝试编写一个函数来转换时间和时间日期到纪元秒,它适用于没有通常的 time_t 库函数的小型系统。我有下面的代码,但计算有点偏差,有人能看出哪里出了问题吗?

long getSecondsSinceEpoch(int h, int m, int s, int day, int month, int year) {
    int i,leapDays;
    long days;
    long seconds;

    const static DAYS_IN_MONTH[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    leapDays = 0;
    days = (year - 1970) * 365;

    for (i = year; i>1970; i--){
        if ((i%4)==0) {
            leapDays++;
        }
    }
    days += leapDays;
    for (i = 1;i < month;i++) {
        days += DAYS_IN_MONTH[i - 1];
    }
    days += day;
    seconds = days * 86400;

    seconds += (h * 3600);
    seconds += (m * 60);
    seconds += s;

    return seconds;
}

I'm trying to write a function to convert a time & date into epoch seconds, it's for a small system that doesn't have the usual time_t library functions. I've got this code below but the calculation is a bit off, can anyone see what's wrong?

long getSecondsSinceEpoch(int h, int m, int s, int day, int month, int year) {
    int i,leapDays;
    long days;
    long seconds;

    const static DAYS_IN_MONTH[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    leapDays = 0;
    days = (year - 1970) * 365;

    for (i = year; i>1970; i--){
        if ((i%4)==0) {
            leapDays++;
        }
    }
    days += leapDays;
    for (i = 1;i < month;i++) {
        days += DAYS_IN_MONTH[i - 1];
    }
    days += day;
    seconds = days * 86400;

    seconds += (h * 3600);
    seconds += (m * 60);
    seconds += s;

    return seconds;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抚笙 2024-11-16 14:51:17

一个错误可能是,在添加闰日时,您可能没有考虑是否在 2 月 29 日之前。但我不确定这是否是唯一的错误。

编辑:我想我发现了第二个错误:您将一整天都添加到几天。您应该在天数中添加 day - 1,因为 1 月 1 日的 08:00 距该月开始仅 8 小时,而不是距该月开始 24+8 小时。

One error is maybe, that you don't take into consideration if you are before February 29th or not when adding the leap days. But I am not sure if this is the only mistake.

EDIT: I think I found the second error: You add all day to days. You should add day - 1 to days, as 08:00 of January 1st is only 8 hours from the start of the month and not 24+8 hours from it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文