计算给定日期的周历(得到某天是周几)

来源:互联网 发布:js判断密码长度 编辑:程序博客网 时间:2024/06/08 09:31

方法1.运用标准库提供的ctime头文件中的struct tm结构

本方法比较好记,思路如下:

1. 获得以tm结构表示的当前日期;

2. 将tm结构体中的年月日换成待转换的年月日;

3. 调用mktime函数将新的tm结构转化为time_t形式的时间表示;

在第3步的过程中tm结构中的tm_wday就会更新为对应待转换年月日的周历了。

#include <iostream>#include <ctime>using namespace std;int main () {int year,month,day;while(cin>>year>>month>>day){time_t mytime = time(0);tm* mytm = localtime(&mytime);mytm->tm_mday=day;mytm->tm_mon=month-1;mytm->tm_year=year-1900;time_t newtime = mktime(mytm);cout<<year<<"-"<<month<<"-"<<day<<" --> 周"    <<(mytm->tm_wday==0?7:mytm->tm_wday)<<endl;}return 0;}


方法2. 运用蔡勒公式
其他计算公式详见蔡勒公式百度百科 http://baike.baidu.com/view/598757.htm
W = [C/4] - 2C + y + [y/4] + [13 * (M+1) / 5] + d - 1

或者是:w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1

若要计算的日期是在1582年10月4日或之前,公式则为

w=y+[y/4]+[c/4]-2c+[13(m+1)/5]+d+3

#include <iostream>using namespace std;int main(){int year,month,day;while(cin >> year >> month >> day){if ( month < 3 ){year -= 1;month += 12;}char b[7][10] = {"Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday","Saturday"};int c = int(year / 100), y = year - 100 * c;int w = int(c / 4) - 2*c +y +int(y/4) +(26 * (month + 1)/10 ) + day - 1;w = ( w % 7 + 7 ) % 7;cout << b[w] << endl;}return 0;}