我想要做的是将纪元时间(自1970年1月1日午夜以来的秒数)转换为"实际"时间(m/d/yh: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;
}
Run Code Online (Sandbox Code Playgroud)
你可以假设成员seconds,minutes,hours,month, …
我正在寻找一种简单的时钟同步协议,该协议易于实现,占用空间小,并且在没有互联网连接的情况下也可以工作,因此可以在封闭的实验室网络中使用.为了清楚起见,我不是在寻找可以仅用于命令事件(例如矢量时钟)的东西,而是能够使不同节点上的进程基于本地时钟同步其动作的东西.据我了解,这需要一个可以考虑时钟漂移的解决方案.可以假设存在TCP/IP或类似的相对低延迟的流连接.
我碰巧发现了Minix的gmtime函数.我对从纪元以来几天计算年份数的位感兴趣.以下是该位的内容:
http://www.raspberryginger.com/jbailey/minix/html/gmtime_8c-source.html
http://www.raspberryginger.com/jbailey/minix/html/loc__time_8h-source.html
#define EPOCH_YR 1970
#define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400)))
#define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)
int year = EPOCH_YR;
while (dayno >= YEARSIZE(year)) {
dayno -= YEARSIZE(year);
year++;
}
Run Code Online (Sandbox Code Playgroud)
看起来算法是O(n),其中n是距历元的距离.此外,LEAPYEAR似乎必须每年单独计算 - 当前日期数十次,未来日期更多.我有以下算法做同样的事情(在这种情况下从ISO-9601纪元(0年= 1 BC)而不是UNIX纪元):
#define CYCLE_1 365
#define CYCLE_4 (CYCLE_1 * 4 + 1)
#define CYCLE_100 (CYCLE_4 * 25 - 1)
#define CYCLE_400 (CYCLE_100 * 4 + 1)
year += 400 * (dayno / CYCLE_400)
dayno = dayno % …Run Code Online (Sandbox Code Playgroud) algorithm ×1
c ×1
c++ ×1
clock ×1
datetime ×1
distributed ×1
epoch ×1
ip ×1
networking ×1
time ×1