获取日期

可以使用mktime()函数来确定给定日期的星期几。 该函数有原型:time_t mktime(struct tm *ptime);

编程学习网为您整理以下代码实例,主要实现:获取日期,希望可以帮到各位朋友。

可以使用mktime()函数来确定给定日期的星期几。 该函数有原型:

time_t mktime(struct tm *ptime);

参考以下代码:

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

int main(voID){
  const char *day[7] = {
                   "Sunday"  , "Monday", "Tuesday", "Wednesday",
                   "Thursday", "FrIDay", "Saturday"
                       };
  const char *month[12] = {
                     "January",   "February", "march",    "April",
                     "May",       "June",     "July",     "August",
                     "September", "October",  "November", "December"
                          };
  const char *suffix[] = { "st", "nd", "rd", "th" };
  enum sufindex { st, nd, rd, th } sufsel = th;  // Suffix selector

  struct tm birthday = {0};                      // A birthday time structure
  char name[30] = {'\0'};

  printf("Enter a name: ");
  gets_s(name, sizeof(name));

  printf("Enter the birthday for %s as day month year integers separated by spaces."
             "\ne.g. For 1st February 1985 enter 1 2 1985 : ", name);
  scanf(" %d %d %d", &birthday.tm_mday, &birthday.tm_mon, &birthday.tm_year);

  birthday.tm_mon -= 1;                          // Month zero-based
  birthday.tm_year -= 1900;                      // Year relative to 1900

  if(mktime(&birthday) == - 1)
  {
    fprintf(stderr, "Operation Failed.\n");
    return -1;
  }

  switch(birthday.tm_mday)
  {
    case 1: case 21: case 31:
      sufsel= st;
      break;
    case 2: case 22:
      sufsel= nd;
      break;
    case 3: case 23:
      sufsel= rd;
      break;
    default:
      sufsel= th;
      break;
  }
  printf("%s was born on the %d%s %s %d, which was a %s.\n", name,
                 birthday.tm_mday, suffix[sufsel], month[birthday.tm_mon],
                            1900 + birthday.tm_year, day[birthday.tm_wday]);
  return 0;
}
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐