最有效的基本日期验证和转换计划?

时间:2013-04-02 23:08:37

标签: java

我打算用Java创建一个程序,用于确定输入的年份是否为闰年和有效日期。考虑到该日期,我希望它转换为完整的书面名称(2013年4月2日= 2013年4月2日),然后确定当年的那一天(2013年4月2日=第92天)。

有很多程序可以做一个或另一个,但是如果可能的话,我会学习如何将它们合二为一的想法。

要检查闰年,这就是我使用的:

public class LeapYear {
    public static void main (String[] args) {
    int theYear;
    System.out.print("Enter the year: ");
    theYear = Console.in.readInt();
    if (theYear < 100) {
        if (theYear > 40) {
        theYear = theYear + 1900;
        }
        else {
        theYear = theYear + 2000;
        }
    }
    if (theYear % 4 == 0) {
        if (theYear % 100 != 0) {
        System.out.println(theYear + " is a leap year.");
        }
        else if (theYear % 400 == 0) {
        System.out.println(theYear + " is a leap year.");
        }
        else {
        System.out.println(theYear + " is not a leap year.");
        }
    }
    else {
        System.out.println(theYear + " is not a leap year.");
    }
    }

}

我意识到我需要改变它以便阅读一年中的月份和日期,但对于这种情况,我只是检查一年。 如何输入相同的日期并将其转换为完整的书面名称?我是否必须创建一个if语句,如:

if (theMonth == 4){
     System.out.println("April");
         if (theDay == 2){
          System.out.print(" 2nd, " + theYear + ".");
         }
    }

这似乎是很多硬编码的工作。我正在尝试限制所需的硬编码量,所以我可以得到类似的东西:

Output:
 Valid entry (4/2/2013).
 It is April 2nd, 2013.
 It is not a leap year.
 It is day 92.

如果出现错误,例如无效日期,我希望程序重新启动用户,直到收到有效条目而不必运行程序(写入'Quit'结束程序时)。

我想我可能只为main方法创建不同的类(获取日期),检查它是否是闰年,转换方法,还是验证方法。

3 个答案:

答案 0 :(得分:1)

public void testFormatDate() throws ParseException {
        final String[] suffixes =
                //    0     1     2     3     4     5     6     7     8     9
                { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
                        //    10    11    12    13    14    15    16    17    18    19
                        "th", "th", "th", "th", "th", "th", "th", "th", "th", "th",
                        //    20    21    22    23    24    25    26    27    28    29
                        "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
                        //    30    31
                        "th", "st" };
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        SimpleDateFormat odf = new SimpleDateFormat("MMMM"); // Gives month name.
        Calendar dayEntered = new GregorianCalendar();
        dayEntered.setTime(sdf.parse("04/02/2013"));
        System.err.println("You chose date: " + odf.format(dayEntered.getTime()) + " " + dayEntered.get(Calendar.DAY_OF_MONTH) + suffixes[dayEntered.get(Calendar.DAY_OF_MONTH)]
        + " " + dayEntered.get(Calendar.YEAR));
        System.err.println("This is " + (((GregorianCalendar)dayEntered).isLeapYear(dayEntered.get(Calendar.YEAR)) ? "" : "not ") + "a leap year.");

        System.err.println("This is day: " + dayEntered.get(Calendar.DAY_OF_YEAR));
    }

答案 1 :(得分:1)

这是一种做法。问题是没有办法在当天制作SimpleDateFormatter打印序号值。我无耻地从here偷了getDayOfMonthSuffix方法。

public static void main(String[] args) {
    final String input = "4/2/2013";
    final SimpleDateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
    final SimpleDateFormat formatter1 = new SimpleDateFormat("MMMM");
    final GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
    final Date date;
    try {
        date = parser.parse(input);
        cal.setTime(date);
    } catch (ParseException ex) {
        System.out.println("Invalid input \"" + input + "\".");
        return;
    }
    if (cal.isLeapYear(cal.get(Calendar.YEAR))) {
        System.out.println("The year is a leap year");
    } else {
        System.out.println("The year is not a leap year");
    }
    System.out.println("The day of the year is " + cal.get(GregorianCalendar.DAY_OF_YEAR));
    final int dayOfMonth = cal.get(GregorianCalendar.DAY_OF_MONTH);
    System.out.println("The date is " +
            formatter1.format(date) +
            " " +
            dayOfMonth +
            getDayOfMonthSuffix(dayOfMonth) +
            ", " +
            cal.get(GregorianCalendar.YEAR));
}

static String getDayOfMonthSuffix(final int n) {
    if (n < 1 || n > 31) {
        throw new IllegalArgumentException("illegal day of month: " + n);
    }
    if (n >= 11 && n <= 13) {
        return "th";
    }
    switch (n % 10) {
        case 1:
            return "st";
        case 2:
            return "nd";
        case 3:
            return "rd";
        default:
            return "th";
    }
}

答案 2 :(得分:0)

因为你需要更多的框架 - 你走了:

package com.yours

import java.io.Console;
import java.util.Calendar;

public class DoStuffWithADate {

    private Calendar parsedDate;

    public static void main(String[] args) {
        DoStuffWithADate soundsNaughty = new DoStuffWithADate();
        System.out.println("Enter a date my friend.  You should use the format: (MM/dd/yyyy)");
        Console theConsole = System.console();
        String enteredDate = theConsole.readLine();

        if (soundsNaughty.isValidDate(enteredDate)) {
            soundsNaughty.writeTheDateInNewFormat();
            soundsNaughty.writeIfItsALeapYear();
            soundsNaughty.writeTheDayOfYearItIs();
        }
    }

    private boolean isValidDate(String enteredDate) {
        //logic goes here.
        parsedDate = null;// if it's valid set the parsed Calendar object up.
        return true;
    }

    private void writeTheDateInNewFormat() {
        System.out.println("The new date format is: ");
    }

    private void writeIfItsALeapYear() {
        System.out.println("The year is a leap year.");
    }

    private void writeTheDayOfYearItIs() {
        System.out.println("The day of year is: ");
    }


}