Convert unix time to date

I execute a function to convert unix time (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;
}

but does not work.

I am testing a function with 1458342000 (today ...), but I am printing> 13-3-2022, what kind of error?

#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
source share
1 answer

There are several problems with your algorithm:

  • the while loop test should be while(x >= 86400), otherwise you turn it off for one day at midnight.
  • you only need to go to the new year, when mes > 12, not >=.
  • the same problem for counting days: you must mark the month, if if (dia > getTotalDaysInMonth(mes, year))otherwise you miss the last day of each month.
  • the code getTotalDaysInMonth(mes, year)looks fine.
  • 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;
}
+3

All Articles