C ++ /转换时间(NULL)到1970年1月1日的确切年,月,周,小时和分钟

时间:2013-06-30 02:02:29

标签: c++ c visual-studio time date-arithmetic

我正在尝试编写从1970年1月1日起计算年数,月数,周数,小时数和分钟数的C ++代码。我包含了我目前的代码。请帮我。提前谢谢。

#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");
}

2 个答案:

答案 0 :(得分:0)

首先,您需要考虑您想要此信息的时区。

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

答案 1 :(得分: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);