日期计算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<stdio.h>
#include<iostream>
using namespace std;
//日期函数
 
int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};
struct date{
    int year,month,day;
};
 
//判闰年
inline int leap(int year){
    return (year%4==0&&year%100!=0)||year%400==0;
}
 
//判合法性
inline int legal(date a){
    if (a.month<0||a.month>12)
        return 0;
    if (a.month==2)
        return a.day>0&&a.day<=28+leap(a.year);
    return a.day>0&&a.day<=days[a.month-1];
}
 
//比较日期大小
inline int datecmp(date a,date b){
   if (a.year!=b.year)
       return a.year-b.year;
   if (a.month!=b.month)
       return a.month-b.month;
   return a.day-b.day;
}
 
//返回指定日期是星期几
int weekday(date a){
    int tm=a.month>=3?(a.month-2):(a.month+10);
    int ty=a.month>=3?a.year:(a.year-1);
    return (ty+ty/4-ty/100+ty/400+(int)(2.6*tm-0.2)+a.day)%7;
}
 
//日期转天数偏移
int date2int(date a){
    int ret=a.year*365+(a.year-1)/4-(a.year-1)/100+(a.year-1)/400,i;
    days[1]+=leap(a.year);
    for (i=0;i<a.month-1;ret+=days[i++]);
    days[1]=28;
    return ret+a.day;
}
 
//天数偏移转日期
date int2date(int a){
    date ret;
    ret.year=a/146097*400;
    for (a%=146097;a>=365+leap(ret.year);a-=365+leap(ret.year),ret.year++);
    days[1]+=leap(ret.year);
    for (ret.month=1;a>=days[ret.month-1];a-=days[ret.month-1],ret.month++);
    days[1]=28;
    ret.day=a+1;
    return ret;
}
 
int main()
{
    date a,b;
    a.year=2014,a.month=8,a.day=28;
    b.year=2014,b.month=8,b.day=29;
    //计算日期之间相差多少天
    int t1=date2int(a);//a的天数
    int t2=date2int(b);//b的天数
    printf("%d\n",t2-t1);
    //计算当前日期过了day天的日期
    int day=1;
    date c=int2date(day+t1);
    printf("%d %d %d",c.year,c.month,c.day);
    return 0;
}

  

posted @   calmound  阅读(428)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
历史上的今天:
2012-08-28 UVA Steps
2012-08-28 UVA The ? 1 ? 2 ? ... ? n = k problem
点击右上角即可分享
微信分享提示