简体   繁体   English

自定义gregoriancalendar月

[英]Custom gregoriancalendar month

How do I instantiate the calendar depending on the input of the user? 如何根据用户的输入实例化日历? I've tried: 我试过了:

Calendar cal = new GregorianCalendar(2011, Calendar.t.getMonth(month), 1);

But didn't do the trick. 但没有做到这一点。

import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Scanner;

public class Test {
    public static void main(String[] args){
        Test t = new Test();
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a month: ");
        String month = sc.next();

        Calendar cal = new GregorianCalendar(2011, Calendar.JANUARY, 1);

        int days = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.out.print("There are "+days+" days in "+month+".");
    }
    private String getMonth(String month){
        return month;
    }
}

Or maybe a more practical way of doing it? 或者更实际的方法呢? Thanks. 谢谢。

You need to add one to the month since it starts from 0 not 1: 您需要在月份中添加一个,因为它从0开始而不是1:

int month = sc.nextInt();
Calendar cal = new GregorianCalendar(2011, month + 1, 1);

or if you want the user to insert a String not a numerical value, then you can do something like: 或者,如果您希望用户插入字符串而不是数字值,则可以执行以下操作:

String month = sc.nextLine();
int iMonth = -1;
if(month.equalsIgnoreCase("January"))  iMonth = 0;
else if(month.equalsIgnoreCase("February")) iMonth = 1;
// and so on ...
Calendar cal = new GregorianCalendar(2011, iMonth, 1);

Use Joda Time instead of native Java GregorianCalendar. 使用Joda Time而不是本机Java GregorianCalendar。 Much, much better! 好多了!

 // From Joda Time documentatio
 // setup date object for midday on Christmas 2004
 Chronology chrono = GregorianChronology.getInstance();
 DateTime dt = new DateTime(2004, 12, 25, 12, 0, 0, 0, chrono);

For every enum, Java has a valueOf(String) static function, that convert a String to the proper enum. 对于每个枚举,Java都有一个valueOf(String)静态函数,它将String转换为适当的枚举。 Unfortunately, the constants of the Calendar class such as Calendar.JANUARY are constants and not enum. 遗憾的是,Calendar类的常量(如Calendar.JANUARY)是常量而不是枚举。 The best for you could be to build an enum with name of months, connect those months to the Calendar constants, and then, after puting to uppercase the input of the user, use the valueOf function. 最好的方法是构建一个名为months的枚举,将这些月份连接到Calendar常量,然后在将用户的输入置为大写之后,使用valueOf函数。

With code : 使用代码:

public enum Months {

    JANUARY (0),
    FEBRUARY (1),
    MARS (2) // and so on

    private int value;

    test(int value){
        this.value = value;
    }
}

And in your class, have a function like this one : 在您的课堂上,有一个像这样的函数:

private int monthFromString(String userInputMonth) {
   return Months.valueOf(userInputMonth);
}

GregorianCalendar不是要直接实例化(读取javadocs),而是使用Calendar.getInstance() ,并使用set(int...)方法赋值。

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

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