4

我正在做一个函数,将 unix 时间转换为日期(dd-mm-yyyy)

stock UnixToTime(x)
{
    new year = 1970;
    new dia = 1;
    new mes = 1;

    while(x > 86400)
    {
        x -= 86400;
        dia ++;

        if(dia == getTotalDaysInMonth(mes, year))
        {
            dia = 1;
            mes ++;

            if (mes >= 12) 
            {
                year ++;
                mes = 1;
            }
        }
    }
    printf("%i-%i-%i", dia, mes, year);
    return x;
}

但不工作。

我正在使用 1458342000(今天...)测试该功能,但打印 > 13-3-2022,有什么错误?

#define IsLeapYear(%1)      ((%1 % 4 == 0 && %1 % 100 != 0) || %1 % 400 == 0)

getTotalDaysInMonth 是这个;

stock getTotalDaysInMonth(_month, year)
{
    new dias[] = {
        31, // Enero
        28, // Febrero
        31, // Marzo
        30, // Abril
        31, // Mayo
        30, // Junio
        31, // Julio
        31, // Agosto
        30, // Septiembre
        31, // Octubre
        30, // Noviembre
        31  // Diciembre
    };
    return ((_month >= 1 && _month <= 12) ? (dias[_month-1] + (IsLeapYear(year) && _month == 2 ? 1 : 0)) : 0);
}
4

1 回答 1

3

你的算法有几个问题:

  • while 循环测试应该是while(x >= 86400),否则你会在午夜关闭一天。
  • 你应该只跳到新年的时候mes > 12,而不是>=
  • 计算天数的同样问题:如果if (dia > getTotalDaysInMonth(mes, year))您跳过每个月的最后一天,您应该勾选月份。
  • 的代码getTotalDaysInMonth(mes, year)似乎还可以。
  • 的代码IsLeapYear可能比通用的格里高利规则更简单,因为在 1970 年和 2099 年之间没有例外。您仍然应该发布它,以防万一出现错误。

这是一个更正的版本:

stock UnixToTime(x) {
    new year = 1970;
    new dia = 1;
    new mes = 1;

    while (x >= 86400) {
        x -= 86400;
        dia++;
        if (dia > getTotalDaysInMonth(mes, year)) {
            dia = 1;
            mes++;
            if (mes > 12) {
                year++;
                mes = 1;
            }
        }
    }
    printf("%i-%i-%i\n", dia, mes, year);
    return x;
}
于 2016-03-19T21:41:49.670 回答