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

时间:2012-08-15 15:32:02

标签: c++

如何按输入日期确定哪一天?

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

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

5 个答案:

答案 0 :(得分: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';

Date to Day of the week algorithm?

答案 1 :(得分:3)

我使用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

答案 2 :(得分:2)

这是一个更简单且可能更好的实现,因为它不需要任何额外的库导入。 返回的结果是从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;
}

答案 3 :(得分: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

答案 4 :(得分: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;
}