2013-06-30 96 views
1

我想写的C++代码,计算年,月,周,小时和分钟从1月1,1970年。我包括我目前拥有的代码。请帮帮我。提前致谢。C++ /转换时间(NULL)到确切的年,月,周,小时和分钟从1970年1月1日

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 


int main(){ 

double seconds, minutes, days, weeks, months, years, hours; 


seconds = time(NULL); 
minutes = seconds/60; 
hours = minutes/60; 
days = hours/24; 
weeks = days/7; 
months = weeks/4; 
years = days/365; 

months = (int) (days/30.42) % 12; 
weeks = (int) (days/7) % 52; 
days = (int) (hours/24) % 24; 
hours = (int) (minutes/60) % 1; 
minutes = (int) (seconds/60) % 60; 


printf("%d years \n", (int)years); 
printf(" %d months \n", (int)months); 
printf(" %d weeks\n", (int)weeks); 
printf(" %d days \n", (int)days); 
printf(" %d minutes\n", (int)minutes); 
printf(" %d hours\n\n", (int)hours); 


system("pause"); 
} 
+0

为什么不使用'localtime'?它会将'time_t'转换为'struct tm',这正是你所需要的。 – Immueggpain

+0

没有闰年逻辑。需要解释魔术常数30.42 –

+0

感谢您的回复。闰年逻辑不是必需的。我认为30.42的常数是为了弥补闰年。不知道,因为我是新来的。 我有问题让系统确切地说什么时间(空)是作为时间值的一个内聚单位。 我希望我可以使用当地时间,但我必须使用上面指定的功能。谢谢你让他们来:) –

回答

0

首先,您需要考虑在哪个时区中需要此信息。

然后,不要自己编写代码,而要使用gmtime_r以UTC或localtime_r的结果获取当前的TZ的本地时区中的结果。

0

您应首先查看标准功能locatime()gmtime()。他们很容易达到你的目标。

time_t t = time(NULL); 
    if (t == -1) { printf("time() failure"); return; } 
    struct tm *tmp; 
    tmp = localtime(&t); 
    if (tmp == NULL) { printf("gmtime() failure"); return; } 
    int seconds = tmp->tm_sec; 
    int minutes = tmp->tm_min; 
    int hours = tmp->tm_hour; 
    int days = tmp->tm_mday + 1; 
    int weeks = (days-1)/7; // OP code has 2 `weeks` calculated, go with week-of-the-month rather than week-of-the-year 
    days -= weeks*7; 
    int months = tmp->tm_mon + 1; 
    int years = tmp->tm_year + 1900; 

    printf("%d years \n", years); 
    printf("%d months \n", months); 
    printf("%d weeks \n", weeks); 
    printf("%d days \n", days); 
    printf("%d hours \n", hours); 
    printf("%d minutes \n", minutes); 
    printf("%d seconds \n", seconds); 

如果你真的想这样做自己,你有一些工作要做。你没有指定时区,所以让我们来看看最简单的:UTC。此外,让我们尽可能简单地在unsigned中执行此操作。如果需要,您可以将其更改为int

// Get the time 
time_t t = time(NULL); 
if (t < 0) { 
    ; // handle this error condition 
} 
unsigned seconds = t%60; 
t /= 60; 
unsigned minutes = t%60; 
t /= 60; 
unsigned hours = t%24; 
t /= 24; 
// now begins the tricky bit. 
// `t` represent the number of days since Jan 1, 1970. 

// I would show more here, but unless I know you are wanting this path, I'd rather not do the work. 


printf("%d years \n", (int)years); 
printf("%d months \n", (int)months); 
printf("%d weeks\n", (int)weeks); 
printf("%d days \n", (int)days); 
printf("%d minutes\n", (int)minutes); 
printf("%d hours\n\n", (int)hours); 
+0

Chux ...谢谢!这更多的是我正在寻找的东西。这非常棘手。我附上了我的最新版本的代码。我知道一些mod是关闭的,因为任何%1都是0,但我仍在解决它。任何有见识的人?感谢所有的回复! –

+0

**代码**'代码' –

+0

我编辑我的帖子上面,以反映我到目前为止。我认为它有点接近...... –

相关问题