转换unix时间戳,以YYYY-MM-DD HH:MM:SS [英] Converting unix timestamp to YYYY-MM-DD HH:MM:SS
问题描述
我有一个Unix时间戳,我需要得到个人的年,月,日,时,分,秒值。所以我在想,如果你们可以帮助我一点我从来没有在数学课非常好:)
I have a Unix timestamp that I need to get the individual year, month, day, hour, minute and second values from. I never was very good in math class so I was wondering if you guys could help me out a little :)
我做的一切我自己(没有time.h中的功能)。语言是C。
I have to do everything myself (no time.h functions). The language is C.
推荐答案
免责声明:以下code不占的闰年 <击>或闰秒 罢工>的 [Unix时间呢不占闰秒。他们是被高估的,反正。 -ed] 的。另外,我没有测试,所以可能有错误。它可能会踢你的猫和侮辱你的母亲。有一个愉快的一天。
Disclaimer: The following code does not account for leap years or leap seconds [Unix time does not account for leap seconds. They're overrated, anyway. -Ed]. Also, I did not test it, so there may be bugs. It may kick your cat and insult your mother. Have a nice day.
让我们尝试一点点伪code(Python的,真的):
Let's try a little psuedocode (Python, really):
# 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这样做应该不会太困难得多。
If I goofed up, please let me know. Doing this in C shouldn't be too much harder.
这篇关于转换unix时间戳,以YYYY-MM-DD HH:MM:SS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!