简体   繁体   English

Java - 几个月和几天?

[英]Java - Months and days?

First of, I have been searching to find anything close to my question but I couldn't find anything. 首先,我一直在寻找任何接近我的问题的东西,但我找不到任何东西。 I am not a very good programmer, I have just started to play with it a little, and my interest for it is growing a lot. 我不是一个非常优秀的程序员,我刚开始玩它一点,我对它的兴趣正在增长很多。

I was thinking if I could make a basic program with basic and easy understandable language, to a month and days "calculator". 我想我是否可以使用基本且易于理解的语言制作一个基本程序,一个月和几天“计算器”。

Like if I have a sysout print which says: Write month number , and I'll type in 11 , and then write a day number in the month and someone writes 27 it will say date correct! 就像我有一个sysout打印文件说: Write month number ,我输入11 ,然后写一个月份的数字,有人写27它会说日期正确!

But if it asks me for month and I'll type 6 , as June and I write in 31 as days it will print which would say Month 6 doesn't have day 31 . 但如果它问了我一个月,我会输入6 ,就像June和我在31日写的那样会打印,这会说第Month 6 doesn't have day 31

I want to keep it simple so I understand like basic language not too hard! 我想保持简单,所以我理解基本语言不太难! I'm just a fresh starter! 我只是一个新手!

Thanks for all help. 谢谢你的帮助。

If you just want to get the job done, I'd suggest you go have a look at the Calendar API or perhaps JodaTime . 如果你只想完成工作,我建议你去看看Calendar API或者JodaTime

If you're more interested in learning how to do it yourself, here's one suggestion for an approach: 如果您对自己学习如何做更感兴趣,这里有一个方法的建议:

Hard-code an array like 硬编码类似的数组

int[] daysInMonths = { 31, 27, 31, ... };

and then check using something along the following lines: 然后使用以下行检查:

// Get month and day from user
Scanner s = new Scanner(System.in);
int month = s.nextInt();
int day = s.nextInt();

int monthIndex = month - 1;     // since array indices are 0-based

if (1 <= day && day <= daysInMonths[monthIndex])
    print ok
else
    print does not exist

This program should get you going... 这个程序应该让你去...

import java.util.*;

class Date {
    public static void main(String[] args) {
        int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        System.out.print("Enter a month number and a day number (separate using \';\':_");
        Scanner sc = new Scanner(System.in).useDelimiter(";");
        int month = sc.nextInt();
        int day = sc.nextInt();
        sc.close();
        System.out.println((day == days[month - 1]) ? "Date correct!" : "Date incorrect: Month " + month + " does not have day " + day);
    }
}

tl;dr TL;博士

Month.of( 6 ).maxLength()

java.time java.time

The modern approach uses the java.time classes that supplant the troublesome old Date / Calendar classes. 现代方法使用java.time类来取代麻烦的旧Date / Calendar类。

Use the Month enum. 使用Month枚举。

Month month = Month.of( 6 ) ;  // Months numbered sanely, 1-12 for January-December.
if( dayOfMonthInput > month.maxLength() ) {
    … bad input
}

Of course for February the last day of month depends on leap year. 当然对于2月,每个月的最后一天取决于闰年。 So if you want to be precise you need to use YearMonth . 因此,如果您想要精确,您需要使用YearMonth

YearMonth ym = YearMonth.of( 2017 , 2 ) ;
if( dayOfMonthInput > ym.lengthOfMonth() ) {
    … bad input
}

About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧遗留日期时间类,如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 And search Stack Overflow for many examples and explanations. 并搜索Stack Overflow以获取许多示例和解释。 Specification is JSR 310 . 规范是JSR 310

Where to obtain the java.time classes? 从哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

in Date class, the first month January is "0", ZERO. 在Date类中,1月的第一个月是“0”,ZERO。 So you think June and you write 6, but must be 5; 所以你认为六月和你写6,但必须是5; as

January 0
February 1
March 2
April 3
May 4
June 5

Leveraging the functionality of the Calendar class is a far better way to do this. 利用Calendar类的功能是一种更好的方法。

    int day = 31;
    int month = 6; // JULY

    Calendar calendar = Calendar.getInstance();
    if(month < calendar.getActualMinimum(Calendar.MONTH) 
            || month > calendar.getActualMaximum(Calendar.MONTH))
        System.out.println("Error - invalid month");
    else 
    {
        calendar.set(Calendar.MONTH, month);
        if (day <  calendar.getActualMinimum(Calendar.DAY_OF_MONTH) 
                || day > calendar.getActualMaximum(Calendar.DAY_OF_MONTH))
        {
            System.out.println("Error - invalid day for month");
        }
        else
        {
            System.out.println("Date is correct");
        }
    }
}

All you have to be aware of is that Calendar currently treats January as month 0. 您需要注意的是,Calendar 目前将1月视为0月。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM