1

我正在尝试编写 C++ 代码来计算自 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");
}
4

2 回答 2

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);  
于 2013-06-30T03:58:56.133 回答
0

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

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

于 2013-06-30T03:51:13.800 回答