4

i'm doing a function, to convert unix time to date (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 not work.

I am testing the function with 1458342000 (today...) but print > 13-3-2022, what's the error?

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

getTotalDaysInMonth is this;

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);
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
iZume
  • 119
  • 1
  • 11

1 Answers1

3

There are several problems with your algorithm:

  • the while loop test should be while(x >= 86400), otherwise you are off by one day at midnight.
  • you should only skip to a new year when mes > 12, not >=.
  • the same problem for counting days: you should tick the month if if (dia > getTotalDaysInMonth(mes, year)) otherwise you skip the last day of each month.
  • the code for getTotalDaysInMonth(mes, year) seems OK.
  • the code for IsLeapYear can be simpler than the generic Gregorian rule since there are no exceptions between 1970 and 2099. You should still post it just in case there is an error there.

Here is a corrected version:

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • Thanks, you're right. And forgiveness, and I added it. IsLeapYear function is the basic often used.. ((%1 % 4 == 0 && %1 % 100 != 0) || %1 % 400 == 0) – iZume Mar 19 '16 at 21:44
  • it's works! thanks!, just i have a question, in my country is 19-03-16, is correctly? or i will add +1 to the day counter? – iZume Mar 19 '16 at 21:54
  • The time function return the number of seconds in UTC time. If you are more than 1 hour east of London, it is already Sunday there, but 19-03-2016 is correct in UTC as of this post. To get local time and date, add the number of seconds of the time difference before calling the function. – chqrlie Mar 19 '16 at 22:13