如何在C语言中查找当前日期?

8

我可以获取当前日期,但输出格式为9/1/2010,我的要求是以“星期三”的形式获取当前日期,而不是像1这样的整数值。以下是我的代码。

#include <dos.h>
#include <stdio.h>
#include<conio.h>

int main(void)
{
struct date d;
getdate(&d);
printf("The current year is: %d\n", d.da_year);
printf("The current day is: %d\n", d.da_day);
printf("The current month is: %d\n", d.da_mon);
getch();
return 0;

}

请帮我找到当前日期所对应的星期几,例如:星期日、星期一......谢谢。

5个回答

11

您是真的在为16位DOS编写代码,还是只是使用了一些古老的奇怪教程?

strftime 在任何现代 C 库中都可用:

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

int main(void) {
    char buffer[32];
    struct tm *ts;
    size_t last;
    time_t timestamp = time(NULL);

    ts   = localtime(&timestamp);
    last = strftime(buffer, 32, "%A", ts);
    buffer[last] = '\0';

    printf("%s\n", buffer);
    return 0;
}

http://ideone.com/DYSyT


这并不会给你日期,它只是格式化日期,以便你需要的信息在中间某个位置。 - Nikita

4
您使用的标题不符合标准。请使用标准函数:
#include <time.h>

struct tm *localtime_r(const time_t *timep, struct tm *result);

调用上述函数后,您可以从中获取工作日:
tm->tm_wday

请查看这个教程/示例

这里有更多带有示例的文档

正如其他人指出的那样,一旦你有了一个tm,你可以使用strftime来获取星期几的名称。这里有一个很好的例子

   #include <time.h>
   #include <stdio.h>
   #include <stdlib.h>
   int
   main(int argc, char *argv[])
   {
       char outstr[200];
       time_t t;
       struct tm *tmp;

       t = time(NULL);
       tmp = localtime(&t);
       if (tmp == NULL) {
           perror("localtime");
           exit(EXIT_FAILURE);
       }

       if (strftime(outstr, sizeof(outstr), "%A", tmp) == 0) {
           fprintf(stderr, "strftime returned 0");
           exit(EXIT_FAILURE);
       }

       printf("Result string is \"%s\"\n", outstr);
       exit(EXIT_SUCCESS);
   }

2

如果你坚持使用过时的编译器,可以在<dos.h>中找到一个dosdate_t结构体:

注:本句中的“过时的编译器”指的是不再被官方支持或更新的编译器。

struct dosdate_t {
  unsigned char  day;       /* 1-31          */
  unsigned char  month;     /* 1-12          */
  unsigned short year;      /* 1980-2099     */
  unsigned char  dayofweek; /* 0-6, 0=Sunday */
};

你需要填写以下内容:

void _dos_getdate(struct dosdate_t *date);

1

0

strftime 绝对是正确的方法。当然,你也可以这样做

char * weekday[] = { "Sunday", "Monday",
                       "Tuesday", "Wednesday",
                       "Thursday", "Friday", "Saturday"};
char *day = weekday[d.da_day];

当然,我假设getdate()函数返回的date结构中的值是从0开始的,并以星期日作为一周的第一天。(我没有DOS环境测试。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接