根据Unix时间戳计算时间,不分年月大小,每月三十天,每年按360天计算。开始时间1970/01/01 00:00:00,输入秒数,显示时间
思路一:进位,60秒进1分钟,60分进1小时,24小时进1天,30天进1月,12月进1年,依次建立循环
while (second > 60)
{
second -= 60;
minute += 1;
if (minute == 60)
{
minute = 0;
hour += 1;
if (hour == 24)
{
hour = 0;
day += 1;
if (day == 31)
{
day = 1;
month += 1;
if (month == 13)
{
month = 1;
year += 1;
}
}
}
}
}
完整代码:
string CalculationDate(long long second)
{
int year = 1970, month = 1, day = 1;
int hour = 0, minute = 0;
// 考虑使用计数思想,秒合法,则算出了最终时间
while (second > 60)
{
second -= 60;
minute += 1;
if (minute == 60)
{
minute = 0;
hour += 1;
if (hour == 24)
{
hour = 0;
day += 1;
if (day == 31)
{
day = 1;
month += 1;
if (month == 13)
{
month = 1;
year += 1;
}
}
}
}
}
char buff[] = "1970/01/01 00:00:10";
sprintf(buff,"%d/%02d/%02d %02d:%02d:%02d", year, month, day, hour, minute, second);
return buff;
}
思路二:取整,一年多少秒,一月多少秒,以此类推,依次取年、月、日....
long long minuteSecond = 60;
long long hourSecond = 60*minuteSecond;
long long daySecond = 24*hourSecond;
long long monthSecond = 30*daySecond;
long long yearSecond = 12*monthSecond;
完整代码:
string CalculationDate_OP(long long second)
{
int year = 1970, month = 1, day = 1;
int hour = 0, minute = 0;
// 考虑直接去整的思想
long long minuteSecond = 60;
long long hourSecond = 60*minuteSecond;
long long daySecond = 24*hourSecond;
long long monthSecond = 30*daySecond;
long long yearSecond = 12*monthSecond;
if (second > yearSecond)
{
int x = second/yearSecond;
year += x;
second -= x*yearSecond;
}
if (second > monthSecond)
{
int x = second/monthSecond;
month += x;
second -= x*monthSecond;
}
if (second > daySecond)
{
int x = second/daySecond;
day += x;
second -= x*daySecond;
}
if (second > hourSecond)
{
int x = second/hourSecond;
hour += x;
second -= x*hourSecond;
}
if (second > minuteSecond)
{
int x = second/minuteSecond;
minute += x;
second -= x*minuteSecond;
}
char buff[] = "1970/01/01 00:00:10";
sprintf(buff,"%d/%02d/%02d %02d:%02d:%02d", year, month, day, hour, minute, second);
return buff;
}
测试:
void test()
{
cout<< CalculationDate(10)<<endl;
cout<< CalculationDate(12345678)<<endl;
cout<< CalculationDate_OP(10)<<endl;
cout<< CalculationDate_OP(12345678)<<endl;
}