C++输入日期获取哪一天
C++ get which day by input date
如何通过输入日期获取哪一天?
输入日期示例: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;
}
您应该使用 mktime
和 ctime
并提取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;
}
相关文章:
- C++ Chrono 确定一天是否是周末?
- 编写了一个C++代码来检查表达式是否具有平衡括号并且我的代码未运行.我已经卡了一天了
- 我正在尝试制作一个程序,在添加 n 天(整数)后告诉一个人什么是一天(例如星期一等)
- std::get_time 没有解析一天
- 以秒为单位将时间从纪元转换为一年中的某一天?
- 解决一年中的一天 c++
- Strftime在iOS上返回一周中不正确的一天
- 一个月的最后一天?
- 泽勒全等编码,输出错误的一天
- C++计算一周中未来的一天
- C++输入日期获取哪一天
- 如何从structtm中减去一天,同时确保完整性
- 跨平台获取一天中的时间的方式
- 从日期开始计算一年中的某一天
- 将某个时间增加一天
- 我如何将一年中的某一天(1-365)转换为其等效日期(即2013年1月5日)C++
- C或C++代码,使用时区从epoch时间戳中获取一天中的小时数
- 如何用重载函数对一天中的时间进行乘除,例如10:00和5:00
- mongodbc++查询一天的范围
- 获取系统时间作为一天中的秒数