首页 > 试题广场 >

计算日期到天数转换

[编程题]计算日期到天数转换
  • 热度指数:159099 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
根据输入的日期,计算是这一年的第几天。
保证年份为4位数且日期合法。
进阶:时间复杂度:,空间复杂度:

输入描述:

输入一行,每行空格分割,分别是年,月,日



输出描述:
输出是这一年的第几天
示例1

输入

2012 12 31

输出

366
示例2

输入

1982 3 4

输出

63
#include <iostream>

using namespace std;

int runMon[12] = {31,29,31,30,31,30,31,31,30,31,30,31};
int pingMon[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
int iConverDateToDay(int year, int month, int day)
 {
    int res = 0;
    bool flag = 0;
    if( (year%100 == 0 && year%400 == 0) || (year%100 != 0 && year%4 == 0) )
        flag = 1;
    for(int i = 0; i < month - 1;i++)
    {
        if(flag == 1)
           res += runMon[i];
        else
           res += pingMon[i];
    }
    res += day;
    return res;
 }

int main()
{
    int year, month,day;
    while(cin >> year >> month >> day)
    {
        cout << iConverDateToDay(year, month, day) << endl;
    }
}

发表于 2017-07-15 16:31:02 回复(0)
1、判断闰年平年,确定2月天数
2、判断输入的月、日是否异常,正常则计算
#能被4整除不能被100整除的就是闰年
import sys
for s in sys.stdin:
    try:
        s = s.strip().split(" ")
        y,m,d = [int(i) for i in s]
        if y%4==0 and y%100!=0:
            d2 = 29
        else:
            d2 = 28
        dd = [31, d2, 31, 30,31,30,31,31,30,31,30,31]
        if m<=12 and m>=1:
            if dd[m-1]>=d:
                print(sum(dd[:m-1]) + d)
        else:
            print(-1)
    except:
        pass


发表于 2020-06-08 12:55:42 回复(2)
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int year=0, month=0, day=0;
        int[] commonYear = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        while(sc.hasNext()){
            year = sc.nextInt();
            month = sc.nextInt();
            day = sc.nextInt();
            int days = 0;
            for(int i=0; i<month-1; i++){
                days += commonYear[i];
            }
            days += day;
            if((year%4==0 && year%100!=0) || year%400==0){//闰年
                if(month>2) days++;//月份大于2
            }
            System.out.println(days);
        }
    }
}

发表于 2021-08-16 09:01:45 回复(0)
Switch不用break就好啦~
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        while(scanner.hasNext()){
            int year = scanner.nextInt();
            int month = scanner.nextInt();
            int day = scanner.nextInt();
            int res = dayOfYear(year,month,day);
            System.out.println(res);
        }
    }
    public static int dayOfYear(int year,int month,int day){
        switch (month){
            case 12:
                day += 30;
            case 11:
                day += 31;
            case 10:
                day += 30;
            case 9:
                day += 31;
            case 8:
                day += 31;
            case 7:
                day += 30;
            case 6:
                day += 31;
            case 5:
                day += 30;
            case 4:
                day += 31;
            case 3:{
                if (year%4 == 0 && year%100!=0){
                    day += 29;
                }else
                    day += 28;
            }
            case 2 :
                day += 31;
            case 1:
                day += 0;
        }
        return day;
    }
}


发表于 2020-03-13 14:46:23 回复(0)
import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int year = scanner.nextInt();
            int month = scanner.nextInt();
            int day = scanner.nextInt();
            scanner.nextLine();
            calculateDate(year, month, day);
        }
        scanner.close();
    }
    
    public static void calculateDate(int year, int month, int day) {
        int sumDay = 0;
        // 正常月份(index)对应的天数;
        int[] normMonthDay = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        // 判断是不是闰年,如果是闰年,false;
        boolean isNormYear = year % 4 == 0 ? false : true;
        // 累加除了最后一个月份的天数;
        for (int i = 1; i < month; i++) {
            // 如果是闰年2月,那么闰年2月应为为29天
            if (i == 2 && !isNormYear) {
                sumDay += 29;
                continue;
            }
            sumDay += normMonthDay[i];
        }
        // 加上最后一个月份的天数;
        sumDay += day;
        // 打印答案
        System.out.println(sumDay);
    }
}

编辑于 2019-08-21 16:20:04 回复(1)
  • 主要是清楚什么是闰年
  • 闰年有366天,能整除4但不能整除100的是普通闰年;能整除400的是世纪闰年
  • 然后结合正则表达式进行判断一个月有多少天就行了
import java.util.*;
public class Main
{
    public static void main(String [] args)
    {
        Scanner sc=new Scanner(System.in);
        while(sc.hasNextInt())
        {
            int year=sc.nextInt();
            int month=sc.nextInt();
            int day=sc.nextInt();
            if(isRunNian(year))//如果是闰年
            {
                int sum=0;
                for(int i=1;i<month;i++)
                {
                    sum+=getDaysInAMonth(i,true);                
                }
                sum+=day;
                System.out.println(sum);
            }
            else//如果是平年
            {
                int sum=0;
                for(int i=1;i<month;i++)
                {
                    sum+=getDaysInAMonth(i,false);                
                }
                sum+=day;
                System.out.println(sum);
            }
        }
    }
    private static boolean isRunNian(int year)
    {
        //闰年有366天,其中2月有29天
        //能整除4单不能整除100的年份是普通闰年
        //能整除400的是世纪闰年
        return (year%4==0&&year%100!=0)||(year%400==0);
    }
    private static int getDaysInAMonth(int month,boolean runNian)
    {
        if(runNian)//如果是闰年
        {
            if(month==2)
            {
                return 29;
            }
            else if((""+month).matches("[13578]")||month==10||month==12)//大月
            {
                return 31;
            }
            else if((""+month).matches("[469]")||month==11)//小月
            {
                return 30;
            }
            else
            {
                System.out.println("月份有误!");
                System.out.println(month);
                return 0;
            }
        }
        else//如果是平年
        {
            if(month==2)
            {
                return 28;
            }
            else if((""+month).matches("[13578]")||month==10||month==12)//大月
            {
                return 31;
            }
            else if((""+month).matches("[469]")||month==11)//小月
            {
                return 30;
            }
            else
            {
                System.out.println("月份有误!");
                System.out.println(month);
                return 0;
            }
        }
    }
}
编辑于 2020-02-20 21:08:16 回复(0)
end<-readLines("stdin")
end_1<-gsub("\\ ","",end)
end<-gsub("\\ ","\\-",end)
end_1<-as.numeric(end_1)
begin<-substr(end_1,start=1,stop=4)
begin_01<-c("01")
begin<-paste(begin,begin_01,begin_01,sep = " ")
begin<-gsub("\\ ","\\-",begin)
begin<-as.Date(begin)
end<-as.Date(end)
Days<-difftime(end,begin,units="days")
Days<-gsub("\\ ","\\",Days)
Days<-as.numeric(Days)
Days<-Days+1
cat(Days)
发表于 2022-02-05 22:05:23 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] s = br.readLine().split(" ");
        int year = Integer.valueOf(s[0]);
        int month = Integer.valueOf(s[1]);
        int day = Integer.valueOf(s[2]);
        int sum = 0;
        switch (month-1){
            case 1:sum=31;break;
            case 2:sum=59;break;
            case 3:sum=90;break;
            case 4:sum=120;break;
            case 5:sum=151;break;
            case 6:sum=181;break;
            case 7:sum=212;break;
            case 8:sum=243;break;
            case 9:sum=273;break;
            case 10:sum=304;break;
            case 11:sum=334;break;
            case 12:sum=365;break;
        }
        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {//闰年
            if(month>2){
                sum+=day+1;
            }else {
                sum+=day;
            }
        }else {
            sum+=day;
        }
        System.out.println(sum);
    }
}


发表于 2021-09-23 09:10:14 回复(0)
#include<stdio.h>
#include<stdlib.h>

int main()
{
    char buff = 0;
    int times = 0;
    int year = 0, month = 0, day = 0;
    
    while(scanf("%c",&buff) != EOF)
    {
        if(buff == ' ') times++;
        if(buff >= '0' && buff <= '9' && times == 0)
        {
            year = year*10 + buff - '0';
        }
        if(buff >= '0' && buff <= '9' && times == 1)
        {
            month = month*10 + buff - '0';
        }
        if(buff >= '0' && buff <= '9' && times == 2)
        {
            day = day*10 + buff - '0';
        }
    }
    
    if(year %4 == 0 && year %100 != 0 && year %400 != 0)
    {
        int map[12] = {31,29,31,30,31,30,31,31,30,31,30,31};
        int Ret = 0;
        for(int i = 0; i < month-1; i++)
        {
            Ret += map[i]; 
        }
        Ret += day;
        printf("%d\n",Ret);
    }
    else
    {
        int map[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
        int Ret = 0;
        for(int i = 0; i < month-1; i++)
        {
            Ret += map[i]; 
        }
        Ret += day;
        printf("%d\n",Ret);
    }
    return 0;
    
}


发表于 2021-09-02 10:49:14 回复(0)
#include<iostream>
#include<vector>
using namespace std;
bool Is_Run(int y)
{
    if((y%4==0&&y%100!=0) || y%400==0)
        return true;
    return false;
}
int daynum(int y,int m)
{
    int mon[13]={29,31,28,31,30,31,30,31,31,30,31,30,31};
    if(m==2 && Is_Run(y))
        m=0;
    return mon[m];
}
int main()
{
    int date[3];
    for(int i=0;i<3;i++)
    {
        cin>>date[i];
    }
    int sum=0;
    int day=date[2],month=date[1],year=date[0];
    for(int j=1;j<month;j++)
    {
        sum+=daynum(year,j);
    }
    sum+=day;
    cout<<sum<<endl;
    return 0;
}
发表于 2021-08-06 16:07:45 回复(0)
let line = readline()
arr = line.split(' ')
const year = Number(arr[0])
const moon = Number(arr[1])
const day = Number(arr[2])
let map = {
    '1':31,
    '2':28,
    '3':31,
    '4':30,
    '5':31,
    '6':30,
    '7':31,
    '8':31,
    '9':30,
    '10':31,
    '11':30,
    '12':31
}
// 判断闰年
if(year%4===0 && year%100 !==0) {
    map['2'] = 29
}
let count = 0
for(let i=1; i<= moon; i++) {
    if(i===moon) {
        count += day
    }
    else {
        count += map[i.toString()]
    }
}
console.log(count)
发表于 2021-07-16 17:05:32 回复(0)
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace std;
int main()
{
    int y,m,d;
    int days[]={0,31,28,31,30,31,30,31,31,30,31,30,31}; //1-12月的天数(不含闰年)
    while(cin>>y>>m>>d) {
        int ans=0;
        for(int i=1;i<m;++i)
            ans+=days[i];
        if(m>2 && (y%4==0 && y%100!=0 || y%400==0))
            ans++; //闰月
        ans+=d;
        cout<<ans;
    }
    return 0;
}

编辑于 2021-06-27 16:25:09 回复(0)
java calendar 虽慢但过
import java.util.Calendar;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String[] arr = scanner.nextLine().split(" ");
            Calendar instance = Calendar.getInstance();
            instance.set(Calendar.YEAR, Integer.valueOf(arr[0]));
            instance.set(Calendar.MONTH, Integer.valueOf(arr[1]) - 1);
            instance.set(Calendar.DAY_OF_MONTH, Integer.valueOf(arr[2]));
            System.out.println(instance.get(Calendar.DAY_OF_YEAR));
        }


    }
}



发表于 2021-06-24 21:45:49 回复(0)
import sys

# 计算是否闰年
# 不能被4整除或者能被100整除,但是不能被400整除的是平年,其他是闰年
def func(year):
    if year%4 != 0&nbs***bsp;(year%100 == 0 and year%400 != 0):
        return False
    return True


for line in sys.stdin:
    try:
        num = 0
        mon_lst = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        year, mon, day = [int(i) for i in line.split(' ')]
        # 如果是闰年,2月份改成29年
        if func(year):
            mon_lst[1] = 29
        for i in range(mon-1):
            num += mon_lst[i]
        print(num+day)
    except Exception as ex:
        print(ex)
        pass

发表于 2021-05-01 11:35:14 回复(0)
/*
思路:
平年和闰年:
平年有365天,闰年有366天

判断是平年还是闰年:
如果年非整百年,被4整除就是闰年,否则为平年。
如果年是整百年,被400整除就是闰年,否则为平年。

平年2月有28天,闰年2月有29天。

加上month和day的非法判断

最后计算正常的天数作为答案返回
*/
import java.util.*;

public class Main{
    
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        
        while(in.hasNextLine()){
            int year = in.nextInt();
            int month = in.nextInt();
            int day = in.nextInt();
            in.nextLine();
            //year是否是平年
            /*
            平年365天,闰年366天
            当year为非整百数时,被4整除的是闰年,剩下是平年
            当year为整百数时,被400整除的是闰年,剩下是平年
            平年2月有28天,闰年2月有29天
            */
            boolean isCommonYear = true;
            if((year%100!=0 && year%4==0) || 
               (year%100==0 && year%400==0)){
                isCommonYear = false;
            }
            int[] dayOfMonth = new int[13];
            dayOfMonth[1] = 31;
            dayOfMonth[3] = 31;
            dayOfMonth[5] = 31;
            dayOfMonth[7] = 31;
            dayOfMonth[8] = 31;
            dayOfMonth[10] = 31;
            dayOfMonth[12] = 31;
            dayOfMonth[4] = 30;
            dayOfMonth[6] = 30;
            dayOfMonth[9] = 30;
            dayOfMonth[11] = 30;
            if(isCommonYear){
                dayOfMonth[2] = 28;
            }else{
                dayOfMonth[2] = 29;
            }
            //不符合的情况
            if(month < 1 || month > 12 || day < 1 || day > 31){
                System.out.println(-1);
                continue;
            }
            if(month == 2){
                if((isCommonYear && month > 28) || (!isCommonYear && month > 29)){
                    System.out.println(-1);
                    continue;
                }
            }
            //正常的话计算天数
            int res = 0;
            for(int i = 1;i < month;i++){
                res += dayOfMonth[i];
            }
            res += day;
            System.out.println(res);
        }
    }
    
}


发表于 2021-04-22 10:11:07 回复(1)
#include<stdio.h>
int main()
{
    int year,month,day,time=0,i;
    int a[12] ={31,28,31,30,31,30,31,31,30,31,30,31};
    while((scanf("%d %d %d",&year,&month,&day))!=EOF)
    {
       
        if(year%4==0&&month>2)
        {for(i=0;i<month-1;i++)
            {

                time = a [i]+time;
                
            }
         printf("%d\n",time+day+1);
         time = 0;
    }
             else
        {for(i=0;i<month-1;i++)
            {
                time = a [i]+time;
                
            }
         printf("%d\n",time+day);
         time = 0;
    }
        }
    return 0;
}
建立一个数组来表示月份代表天数,当是闰年而且月份大于2时,天数在数组结果上加一
发表于 2021-04-01 10:58:38 回复(0)
#include <stdio.h>

int main()
{
    int year,month,day;
    int outday;
    while(scanf("%d%d%d",&year,&month,&day) != EOF)
    {
        outday = 0;
        switch(month)
        {
            case 12: outday += 30;
            case 11: outday += 31;
            case 10: outday += 30;
            case 9: outday += 31;
            case 8: outday += 31;
            case 7: outday += 30;
            case 6: outday += 31;
            case 5: outday += 30;
            case 4: outday += 31;
            case 3: 
                if((year%4==0 && year%100!=0) || (year%400==0))
                    outday += 29;
                else
                    outday += 28;
            case 2: outday += 31;
            case 1: 
                break;
            default:
                outday = -1;
                break;
        }
        outday += day;
        printf("%d\n",outday);
    }
    
}

发表于 2021-02-01 12:50:45 回复(0)
#include <iostream>
using namespace std;

//闰年判断
int IsLeapYear(const int year)
{
    return ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)));
}
//同一年内两日期天数差计算(原因是我自己找自己做的搬来的,所以也不想改这里)
int DaysInOneYear(const int year, const int month, const int Lday)
{
    int res = 0;
    for (int i = 1; i < month; i++) {
        switch (i)
        {
        case 4:
        case 6:
        case 9:
        case 11:
            res--;
            break;
        case 2:
            res -= (3 - IsLeapYear(year));
            break;
        }
    }
    res += (month - 1) * 31 + Lday;
    return res;
}
int main()
{
    int year, month, day;
    while (cin >> year >> month >> day) {
        cout << DaysInOneYear(year, month, day) << endl;
    }
    return 0;
}
发表于 2021-01-07 19:53:56 回复(0)
# 方法一:一行代码实现(通过调用现成的方法)
import datetime
while True:
    try:
        print(datetime.datetime(*map(int, input().split())).strftime("%j").lstrip("0"))
    except:
        break

# 方法二:手动计算第几天,练习逻辑
# 注意:应该先对年份进行是否为闰年的判断,若为闰年,将Day的二月份天数更正为29,
#      以便后续在判断非法输入时,二月份所包含的天数为正确的。否则,2000 2 29无法通过。
def outDay(year, month, day):
    # 每个月所包含的天数
    days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    # 如果输入年份为闰年,则将第二月对应的天数改为29天。
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
        days[1] = 29
    # 判断输入的年月日是否合法
    if year <= 0 or month <= 0 or month > 12 or day <= 0 or day > days[month-1]:
        return -1
    # sum为前面month-1个月的天数总和
    sum = 0
    for i in range(month-1):
        sum += days[i]
    return sum + day

while True:
    try:
        year, month, day = map(int, input().strip().split(' '))
        res = outDay(year, month, day)
        print(res)
    except:
        break

编辑于 2020-12-09 20:42:36 回复(0)
Java方法解决,用时一个小时左右的时间
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()){
            String s = sc.nextLine();
            String[] ss = s.split(" ");
            int[] ii = new int[3];
            ii[0] = Integer.parseInt(ss[0]);
            ii[1] = Integer.parseInt(ss[1]);
            ii[2] = Integer.parseInt(ss[2]);
            System.out.println(iConverDateToDay(ii[0],ii[1],ii[2]));
        }
    }

    public static int iConverDateToDay(int year, int month, int day ){
        boolean isLeapYear = false;
        int days = 0;
        if(year%4 == 0 || year %400 ==0 && year % 100!=0){
            isLeapYear = true;
        }
        if (month >= 2) {
            for (int i = 2; i <= month; i++) {
                switch (i) {
                    //默认三月的前一个月:也就是2月是29天
                    case 3:
                        days = days + 29;
                        break;
                    case 5:
                    case 7:
                    case 10:
                    case 12:
                        days = days + 30;
                        break;
                    case 2:
                        days = days + 31;
                        break;
                    case 8:
                    case 4:
                    case 6:
                    case 9:
                    case 11:
                        days = days + 31;
                        break;
                }
            }
            days = days + day;
        } else {
            days = day;
        }

        return (month > 2 && isLeapYear)||(month <= 2)?days:days-1;
    }
}


发表于 2020-09-02 09:59:18 回复(0)