3

如何通过输入日期获得哪一天?

输入日期示例:15-08-2012

我如何知道是星期一、星期二还是使用 C++ 的哪一天。

我试图从一个月的可用日期中省略周末,所以如果我输入例如 2012 年 8 月的月份,我想检查哪一天是星期六,哪一天是星期日,所以我可以从可用日期中省略它对于我的程序。

我尝试获取一个月天数的代码:

if (month == 4 || month == 6 || month == 9 || month == 11)
{
    maxDay = 30;
}
else if (month == 2)
//{
//  bool isLeapYear = (year% 4 == 0 && year % 100 != 0) || (year % 400 == 0);
//  if (isLeapYear)
//  { 
//   maxDay = 29;
//  }
//else
{
    maxDay = 28;
}

我想知道的下一件事是在那个月,哪一天是周末,所以我可以从结果中省略它。

4

5 回答 5

5
#include <ctime>

std::tm time_in = { 0, 0, 0, // second, minute, hour
        4, 9, 1984 - 1900 }; // 1-based day, 0-based month, year since 1900

std::time_t time_temp = std::mktime( & time_in );

// the return value from localtime is a static global - do not call
// this function from more than one thread!
std::tm const *time_out = std::localtime( & time_temp );

std::cout << "I was born on (Sunday = 0) D.O.W. " << time_out->tm_wday << '\n';

日期到星期几算法?

于 2012-08-15T15:39:24.900 回答
3

我会用mktime(). 给定日、月和年,填写 a tm,然后调用mktime它:

tm timeStruct = {};
timeStruct.tm_year = year - 1900;
timeStruct.tm_mon = month - 1;
timeStruct.tm_mday = day;
timeStruct.tm_hour = 12;    //  To avoid any doubts about summer time, etc.
mktime( &timeStruct );
return timeStruct.tm_wday;  //  0...6 for Sunday...Saturday
于 2012-08-15T15:49:25.693 回答
2

这是一个更简单且可能更好的实现,因为它不需要任何额外的库导入。返回的结果是一个从 0 到 6 的整数(星期日、星期一、星期二...星期六)。

#include <iostream>

int dayofweek(int d, int m, int y){
    static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
    y -= m < 3;
    return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}

/* Driver function to test above function */
int main(){
    int day = dayofweek(23, 10, 2013); 
    // Above statement finds the week day for 10/23/2013
    //dayofweek(<day in month>,<month>,<year>)
    std::cout << day;
    return 0;
}
于 2014-10-10T19:48:07.370 回答
1

您应该使用mktimectime提取结构的tm_wday字段tm。保证mktime不需要该字段,因此您可以填充骨架tm结构,对其进行处理并将其分解回完整的结构:

#include <ctime>

std::tm t = {};
t.tm_mday = 15;
t.tm_mon = 8;
t.tm_year = 2012;

std::tm * p = std::localtime(std::mktime(&t));

// result is p->tm_wday
于 2012-08-15T15:40:01.770 回答
0
#include <stdio.h>
#include <time.h>

int main ()
{
  char *str = "15-08-2012";
  struct tm tm; 
  if (strptime (str, "%d-%m-%Y", &tm) == NULL) {
    /* Bad format !! */
  }
  char buffer [80];
  strftime (buffer, 80, "Day is %a", &tm);
  puts (buffer);    
  return 0;
}
于 2012-08-15T15:42:53.623 回答