【发布时间】:2010-12-14 02:42:26
【问题描述】:
我想要做的是将纪元时间(自 1970 年 1 月 1 日午夜以来的秒数)转换为“实时”时间(m/d/y h:m:s)
到目前为止,我有以下算法,我觉得有点难看:
void DateTime::splitTicks(time_t time) {
seconds = time % 60;
time /= 60;
minutes = time % 60;
time /= 60;
hours = time % 24;
time /= 24;
year = DateTime::reduceDaysToYear(time);
month = DateTime::reduceDaysToMonths(time,year);
day = int(time);
}
int DateTime::reduceDaysToYear(time_t &days) {
int year;
for (year=1970;days>daysInYear(year);year++) {
days -= daysInYear(year);
}
return year;
}
int DateTime::reduceDaysToMonths(time_t &days,int year) {
int month;
for (month=0;days>daysInMonth(month,year);month++)
days -= daysInMonth(month,year);
return month;
}
您可以假设成员seconds、minutes、hours、month、day 和year 都存在。
使用for 循环修改原来的时间感觉有点不对劲,我想知道是否有“更好”的解决方案。
【问题讨论】:
-
仅仅调用
time.h公开的这个功能有什么问题,例如gmtime 如果您要的是 GMT 而不是某个特定的时区? -
没什么问题,我什至不知道它存在。谢谢!但是,我仍然很想知道我的实现如何才能做得更好。
-
@Austin,“谢谢”和不赞成不符合正常的 SO 礼仪!-)
-
(让我赶紧指出这不是自私自利的,因为无论如何我今天已经筋疲力尽了:这是关于 SO 基本礼仪的顺利和正常应用——你投票回答你找到有用的!!!)。
-
好的,所以我知道您正在寻找程序解决方案...但如果您还没有看到它,请查看epochconverter.com。这是检查您的工作的非常有用的方法:)
标签: c++ algorithm datetime epoch