【发布时间】:2013-04-03 20:36:37
【问题描述】:
我写了一个简单的函数来用当前的年、月和日填充三个变量。 但是,由于某种原因,它无法正常工作,而且我似乎找不到问题所在。
void getDate(int *year, int *month, int *date)
{
int epochTime,
monthLength,
functionYear,
functionMonth,
functionDate;
functionYear = 1970;
functionMonth = 1;
functionDate = 1;
epochTime = time(NULL);
while (epochTime > 1 * 365 * 24 * 60 * 60)
{
epochTime -= 1 * 365 * 24 * 60 * 60;
functionYear++;
}
monthLength = findMonthLength(functionYear, functionMonth, false);
while (epochTime > 1 * monthLength * 24 * 60 * 60)
{
printf("%d\n", epochTime);
epochTime -= 1 * monthLength * 24 * 60 * 60;
functionMonth++;
monthLength = findMonthLength(functionYear, functionMonth, false);
printf("functionMonth = %d\n", functionMonth);
}
while (epochTime > 1 * 24 * 60 * 60)
{
printf("%d\n", epochTime);
epochTime -= 1 * 24 * 60 * 60;
functionDate++;
printf("functionDate = %d\n", functionDate);
}
*year = functionYear;
*month = functionMonth;
*date = functionDate;
}
findMonthLength() 返回一个整数值,它是发送月份的长度。 1 = 一月等。它使用年份来测试是否是闰年。
现在是 2013 年 4 月 3 日;但是,我的函数找到了 4 月 15 日,我似乎找不到问题所在。
编辑: 我知道了。我的第一个问题是,虽然我记得在查找月份时检查闰年,但在查找每年时却忘记了这一点,这让我休息了好几天。 我的第二个问题是我没有从 UTC 转换为本地时区
【问题讨论】:
-
printf仅在代码中,因为我正在尝试调试它。 -
您确实意识到一年中没有
365*24*60*60秒,对吧?闰年是有原因的…… -
你在确定年份时没有考虑闰年,我怀疑你没有把 2000 年算作闰年。
-
@twalberg:4 次中有 3 次还不错。 ;-)
-
您的更新在检查闰年时有
while ...循环,这可能不太正确......这将基本上选择一个循环,具体取决于您的开始年份是闰年,而不是决定每年...
标签: c unix-timestamp