已知日期转天数;已知天数转日期
核心是判断闰年,可见:C语言判断闰年
//编译环境vs 2019
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
using namespace std;
#include <string>
int year = 0, sum = 0, month = 0, day = 0;
bool leapYear(int year);
int leapMonth[12] = {
31,29,31,30,31,30,31,31,30,31,30,31 };
int noleapMonth[12] = {
31,28,31,30,31,30,31,31,30,31,30,31 };
void schema1();
void schema2();
void main()
{
int year = 0, sum = 0, month = 0, day = 0;
int key = 0;
printf("1.日期转天数:输入x年x月x日,输出第x天\n2.天数转日期:输入x年第x天,输出x年x月x日\n");
scanf("%d",&key);
switch (key)
{
case 1:schema1(); break;
case 2:schema2(); break;
default:break;
}
}
void schema1()
{
printf("\n请输入:xxxx-xx-xx:\n");
string str;
cin >> str;
int year, month, day;
year = stoi(str.substr(0, 4));
month = stoi(str.substr(5, 7));
day = stoi(str.substr(8, 10));
//printf("%d %d %d", year, month, day);
//至此,年,月,日已经安排好
int sum = 0;
if (leapYear(year)) //如果是闰年,则一年有366天
{
//先判断是否是闰年,再判断是哪一个月
for (int k = 0; k < month - 1; k++)
{
sum += leapMonth[k];
}
sum += day;
}
else
{
for (int k = 0; k < month - 1; k++)
{
sum += noleapMonth[k];
}
sum += day;
}
printf("\n%d\n", sum);
}
void schema2()
{
printf("\n请输入:xxxx xxx:\n");
scanf("%d", &year);
scanf("%d", &sum);
if (leapYear(year)) //先判断是否闰年
{
// printf("闰年\n");
for (int i = 0; sum > 0; i++)
{
month += 1;
day = sum;
sum -= leapMonth[i];
}
}
else
{
// printf("闰年\n");
for (int i = 0; sum > 0; i++)
{
month += 1;
day = sum;
sum -= noleapMonth[i];
}
}
printf("\n%d-%d-%d\n", year, month, day);
}
bool leapYear(int year)
{
if(year % 4 == 0 && year % 100 != 0|| year % 400 == 0)
return true;
else
return false;
}