C

时间:2017-03-02 23:57:30

标签: c windows mingw iso8601 strftime

我正在尝试使用C. MinGW在我的电脑上安装ISO8601周数。 GCC版本是5.3.0。你可以在下面看到我的代码。 strftime 不适用于说明符"%V"。但它适用于说明符"%W"。但这不是我想要的。我需要ISO 8601格式的周数。

我用2个不同的在线C编译器尝试了我的代码,它们都运行良好。我怀疑我的电脑上的编译器没有很好地配置。谁能告诉我我做错了什么?任何帮助将不胜感激。

这是我的代码:

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

int main ()
{
    time_t timep;
    struct tm * time_inf;
    char buff [80];

    time ( &timep );
    time_inf = localtime ( &timep );

    time_inf->tm_year = 2008 - 1900;
    time_inf->tm_mon = 11;
    time_inf->tm_mday = 31;

    mktime ( time_inf );

    strftime (buff, sizeof(buff), "%V", time_inf) ;
    puts (buff); //prints nothing

    printf("%d", strlen(buff)); //prints 0

    return 0;
}

2 个答案:

答案 0 :(得分:2)

MinGW不提供自己的strftime,而是MSVCRT定义中的链接which doesn't provide %V

要么实现自己缺少的东西,要么使用替代实现,例如 here's BSD's strftime

答案 1 :(得分:2)

  

用C

获取ISO8601周数

"%V" strftime()不可用或有问题时,代码可以指向性计算ISO 8601周。

ISO 8601 一年中周一开始。

当想要找到一年中的ISO 8601 week时,通常是相应的&#34;年&#34;也需要。

一年中的第一周,即第一周,是从星期一开始的第一周,即1月份至少有4天 - 或者根据以下代码使用,第一周的第一周是第1周。 / p>

12月31日是否可能在明年的第1周 1月1日是否可能在上一年的第52/53周。

#include <time.h>

// return 1 on failure, 0 on success
int tm_YearWeek(const struct tm *tmptr, int *year, int *week) {
  // work with local copy
  struct tm tm = *tmptr;
  // fully populate the yday and wday fields.
  if (mktime(&tm) == -1) {
    return 1;
  }

  // Find day-of-the-week: 0 to 6.
  // Week starts on Monday per ISO 8601
  // 0 <= DayOfTheWeek <= 6, Monday, Tuesday ... Sunday
  int DayOfTheWeek = (tm.tm_wday + (7 - 1)) % 7;

  // Offset the month day to the Monday of the week.
  tm.tm_mday -= DayOfTheWeek;
  // Offset the month day to the mid-week (Thursday) of the week, 3 days later.
  tm.tm_mday += 3;
  // Re-evaluate tm_year and tm_yday  (local time)
  if (mktime(&tm) == -1) {
    return 1;
  }

  *year = tm.tm_year + 1900;
  // Convert yday to week of the year, stating with 1.
  *week = tm.tm_yday / 7 + 1;
  return 0;
}

实施例

int main() {
  struct tm tm = { 0 };
  tm.tm_year = 2008 - 1900;
  tm.tm_mon = 12 - 1;
  tm.tm_mday = 31;
  tm.tm_isdst = -1;
  int y = 0, w = 0;
  int err = tm_YearWeek(&tm, &y, &w);
  printf("Err:%d  Year:%d  Week:%d %02d%02d\n", err, y, w, y%100, w);
  return 0;
}

产出是2009年12月31日的2009年第1周或 0901 。根据上面的讨论,这是可以预期的,并且可以解释OP对OP代码的未陈述的关注。

Err:0  Year:2009  Week:1 0901