【问题标题】:How to keep user typed dates within this format "yyyy/MM/dd" and within actual calendar dates如何将用户键入的日期保持在这种格式“yyyy/MM/dd”和实际日历日期内
【发布时间】:2016-03-16 03:22:16
【问题描述】:

我正在尝试使用户无法键入无效的日期。例如,如果用户输入 2017/03/15,它会抛出一个错误并提醒用户这是无效的(让用户绑定到当前和过去的日期),或者对于以下任何示例都会抛出错误 Mar 2016 年 15 月(

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;

private void addDVD() {
        ConsoleIO con = new ConsoleIO();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        Date testDate = null;

        boolean alive = true;
        while (alive) {

            String date = con.readString("Please enter Release Date. (yyyy/MM/dd)");

            try {
                testDate = sdf.parse(date);
                alive = false;
            } catch (ParseException e) {
                con.print("Incorrectly typed date. Try again please. (yyyy/MM/dd)");
            } 
            if (!sdf.format(testDate).equals(date)){
                con.print("The date you provided is invalid.");
            }
        }


        DVD dvd = new DVD();

        dvd.setReleaseDate(Integer.parseInt(testDate.toString()));
}

【问题讨论】:

  • 基本答案是,你不能也不应该。日期类只是自给定时间点以来毫秒数的容器,它们没有我格式化的概念。当您需要显示这些值时,您可以根据需要使用 DateFormatter
  • 使用 DateFormat Ro 将字符串解析为日期(您可能需要将生成的日期格式化回字符串并将其与原始数据进行比较以确定)。如果您不想要时间,那么您应该考虑使用 LocalDate 代替,删除时间部分比您想的要复杂

标签: java date exception calendar formatting


【解决方案1】:

您应该为当前时间创建一个新的 long。

long today = System.currentTimeMillis();

然后使用它来标记日期是否早于当前日期。

if(testDate.getTime() > today) {
    System.out.println("bad input");
}

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    相关资源
    最近更新 更多