我正在执行一项功能,以将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);
}
您的算法有几个问题:
while(x >= 86400)
,否则您将在午夜一天之前离开。mes > 12
,而不是>=
。if (dia > getTotalDaysInMonth(mes, year))
不跳过每个月的最后一天,则应勾选月份。getTotalDaysInMonth(mes, year)
似乎还可以。IsLeapYear
可以比通用Gregorian规则更简单,因为在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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句