我有一个Unix时间戳,我需要从中获取各个年,月,日,小时,分钟和秒的值。我在数学课上从来都不是很出色,所以我想知道你们是否可以帮我一点忙:)
我必须自己做所有事情(没有time.h函数)。语言是C。
最佳答案
免责声明:以下代码不解释leap years或leap seconds [Unix时间不解释leap秒。无论如何,他们被高估了。 -Ed]。另外,我没有进行测试,因此可能存在错误。它可能会踢您的猫并侮辱您的母亲。祝你今天过得愉快。
让我们尝试一些伪代码(Python,实际上):
# Define some constants here...
# You'll have to figure these out. Don't forget about February (leap years)...
secondsPerMonth = [ SECONDS_IN_JANUARY, SECONDS_IN_FEBRUARY, ... ]
def formatTime(secondsSinceEpoch):
# / is integer division in this case.
# Account for leap years when you get around to it :)
year = 1970 + secondsSinceEpoch / SECONDS_IN_YEAR
acc = secondsSinceEpoch - year * SECONDS_IN_YEAR
for month in range(12):
if secondsPerMonth[month] < acc:
acc -= month
month += 1
month += 1
# Again, / is integer division.
days = acc / SECONDS_PER_DAY
acc -= days * SECONDS_PER_DAY
hours = acc / SECONDS_PER_HOUR
acc -= hours * SECONDS_PER_HOUR
minutes = acc / SECONDS_PER_MINUTE
acc -= minutes * SECONDS_PER_MINUTE
seconds = acc
return "%d-%d-%d %d:%d%d" % (year, month, day, hours, minutes, seconds)
如果我发呆了,请告诉我。在C中执行此操作应该不会太困难。