将unix时间转换为日期

时间:2016-03-19 21:32:22

标签: c algorithm pawn

我正在执行一项功能,将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);
}

1 个答案:

答案 0 :(得分: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;
}
相关问题