将时间/日期转换为纪元(自 1970 年以来的秒数)
我正在尝试编写一个函数来转换时间和时间日期到纪元秒,它适用于没有通常的 time_t 库函数的小型系统。我有下面的代码,但计算有点偏差,有人能看出哪里出了问题吗?
long getSecondsSinceEpoch(int h, int m, int s, int day, int month, int year) {
int i,leapDays;
long days;
long seconds;
const static DAYS_IN_MONTH[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
leapDays = 0;
days = (year - 1970) * 365;
for (i = year; i>1970; i--){
if ((i%4)==0) {
leapDays++;
}
}
days += leapDays;
for (i = 1;i < month;i++) {
days += DAYS_IN_MONTH[i - 1];
}
days += day;
seconds = days * 86400;
seconds += (h * 3600);
seconds += (m * 60);
seconds += s;
return seconds;
}
I'm trying to write a function to convert a time & date into epoch seconds, it's for a small system that doesn't have the usual time_t library functions. I've got this code below but the calculation is a bit off, can anyone see what's wrong?
long getSecondsSinceEpoch(int h, int m, int s, int day, int month, int year) {
int i,leapDays;
long days;
long seconds;
const static DAYS_IN_MONTH[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
leapDays = 0;
days = (year - 1970) * 365;
for (i = year; i>1970; i--){
if ((i%4)==0) {
leapDays++;
}
}
days += leapDays;
for (i = 1;i < month;i++) {
days += DAYS_IN_MONTH[i - 1];
}
days += day;
seconds = days * 86400;
seconds += (h * 3600);
seconds += (m * 60);
seconds += s;
return seconds;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个错误可能是,在添加闰日时,您可能没有考虑是否在 2 月 29 日之前。但我不确定这是否是唯一的错误。
编辑:我想我发现了第二个错误:您将一整天都添加到几天。您应该在天数中添加 day - 1,因为 1 月 1 日的 08:00 距该月开始仅 8 小时,而不是距该月开始 24+8 小时。
One error is maybe, that you don't take into consideration if you are before February 29th or not when adding the leap days. But I am not sure if this is the only mistake.
EDIT: I think I found the second error: You add all day to days. You should add day - 1 to days, as 08:00 of January 1st is only 8 hours from the start of the month and not 24+8 hours from it.