2016-03-19 38 views
4

我正在做一个功能,UNIX时间转换为日期(DD-MM-YYYY)转换Unix时间去约会

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 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); 
} 
+0

还张贴'IsLeapYear'的代码。 – chqrlie

+0

如果你需要类似的东西来制作,我会看看这个只包含头文件的库:https://github.com/HowardHinnant/date – MikeMB

+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; 
} 
+0

相似,谢谢,你是对的。 和宽恕,我添加它。 IsLeapYear函数是基本常用的。((%1%4 == 0 &&%1%100!= 0)||%1%400 == 0) – iZume

+0

我已经做了更改,现在打印:10.12。 2017年。 – iZume

+0

@Spitzer:同样的问题的日子... – chqrlie