C++输入日期获取哪一天

C++ get which day by input date

本文关键字:一天 获取 日期 输入 C++      更新时间:2023-10-16

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

输入日期示例: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;
}

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

#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';

日期到星期几算法?

我会使用mktime(). 给定日、月和年,填写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

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

#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;
}

您应该使用 mktimectime 并提取tm结构的tm_wday字段。保证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
#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;
}