以mm/dd/yyyy格式读取并打印日期

BBK*_*Kay 0 java

我是Java新手,我正在编写一个Java程序,它以mm/dd/yyyy格式读取日期,并以日,年格式打印出日期.该计划必须验证年份是在1900年至2014年之间(包括两个限制),并且日期和月份和年份是有效且相互一致的.如果输入不正确,程序必须显示相应的消息并终止.如果输入正确,则应以指定的格式打印输出.

例如:输入日期2013年4月30日2013年4月30日

输入日期01/12/1888年份应在1900年至2014年之间

我坚持如何限制年份和日期(如2月只有28),以及如何打印出类似上面的例子.我想对这个问题使用if else和switch语句.这是我到目前为止的代码,感谢您的帮助.

import java.util.Scanner;
public class Dates {
public static void main(String[] args) {
    int month, day, year;
    Scanner input = new Scanner(System.in);
    System.out.print("Please Enter Date in The Format mm/dd/yyyy : ");
    month = input.nextInt();
    day = input.nextInt();
    year = input.nextInt();
    String months = "January February March April May June July August "
            + "September October November December";
    String January = months.substring(0,7);
    String February = months.substring(8,16);
    String March = months.substring(17,22);
    String April = months.substring(23,28);
    String May = months.substring(29,32);
    String June = months.substring(33,37);
    String July = months.substring(38,42);
    String August = months.substring(43,49);
    String September = months.substring(50,59);
    String October = months.substring(60,67);
    String November = months.substring(68,76);
    String December = months.substring(77,85);
    if (month == 1) {
        months = January;
        day = 31;
    }
    else if (month == 2) {
        months = February;
        day = 28;
    }
    else if (month == 3) {
        months = March;
        day = 31;
    }
    else if (month == 4) {
        months = April;
        day = 30;
    }
    else if (month == 5) {
        months = May;
        day = 31;
    }
    else if (month == 6) {
        months = June;
        day = 30;
    }
    else if (month == 7) {
        months = July;
        day = 31;
    }
    else if (month == 8) {
        months = August;
        day = 31;
    }
    else if (month == 9) {
        months = September;
        day = 30;
    }
    else if (month == 10) {
        months = October;
        day = 31;
    }
    else if (month == 11) {
        months = November;
        day = 30;
    }
    else if (month == 12) {
        months = December;
        day = 31;
    }
    else {
        System.out.print("Invalid Month");
    }

    if (year >= 1900 || year <= 2014) {
        System.out.print(year);
    }
    else {
        System.out.println("Year should be between 1900 and 2014");
    }
    System.out.println(months + " " + day + ", " + year);
  }
 }
Run Code Online (Sandbox Code Playgroud)

Kee*_*san 8

在Java中分别使用CalendarSimpleDateFormat用于处理和格式化日期.那是个不错的选择!除非您正在学习过程中,否则请不要重新发明轮子.

请阅读CalendarSimpleDateFormat API 的文档