您如何比较 Java 中的日期、之前的日期和未来的日期?

How do you compare date, previous date and future date in Java?

在注册一个人之前,我需要验证出生日期不早于之前的日期,例如(01/01/1970) 和当前日期。

对我不起作用的方法:

 public void agregarPersona() throws Exception {
            ImplPersonaD dao;
            try {
            Date date = new Date();
            DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
            String fechaActual = String.valueOf(dateFormat.format(date));      
            String fechaPasada = "01/01/1970";
                if(fechaPasada  > persona.getFechNac() <= fechaActual ){
                dao = new ImplPersonaD();
                dao.agregarPersona(persona);
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Satisfactorio", "Ingresado correctamente"));
              }
               else{
               FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Invalido", "Fecha invalida"));
                 }
            } catch (Exception e) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Hubo un problema"));
            }
        }

以下行是无效的,不要做你认为应该做的事:

String fechaActual= String.valueOf(Calendar.DATE/Calendar.MONTH/Calendar.YEAR);        
String fechaPasada = "01/01/1970";
if(fechaPasada  > persona.getFechNac() <= fechaActual ){

您似乎想要检查 persona.getFechNac() 返回的值是否为 1970 年 1 月 1 日之后且早于或等于当前日期的日期。

正确的做法是这样的:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

// ...

LocalDate fechaActual = LocalDate.now();
LocalDate fechaPasada = LocalDate.of(1970, 1, 1);

LocalDate fechNac = LocalDate.parse(persona.getFechNac(),
                            DateTimeFormatter.ofPattern("dd/MM/yyyy"));

if (fechNac.isAfter(fechaPasada) && fechaActual.isBefore(fechNac)) {
    // ...
}

我在这里假设 persona.getFechNac() returns 一个 String 包含 dd/MM/yyyy.

格式的日期

tl;博士

使用现代 类,特别是 LocalDate.

LocalDate                                        // Represent a date-only value without a time-of-day and without a time zone or offset-from-UTC.
.parse(
    "21/01/1966" ,                               // String in some localized format. 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" )  // Specify formatting pattern to match input string.
)                                                // Returns a `LocalDate` object.
.isBefore(                                       // Compare one `LocalDate` to another.
    LocalDate.EPOCH                              // 1970-01-01
)                                                // Returns a boolean.

true

java.time

仅使用现代 java.time 类,从不使用 SimpleDateFormatCalendar

LocalDate

LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

正在解析

定义格式模式以匹配您的输入字符串。

String input = "01/01/1970" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate limit = LocalDate.parse( input , f ) ;

当前日期

获取今天的日期。

时区对于确定日期至关重要。对于任何给定时刻,日期在全球范围内因地区而异。例如,Paris France is a new day while still “yesterday” in Montréal Québec.

午夜后几分钟

如果未指定时区,JVM 将隐式应用其当前默认时区。该默认值在运行时可能 change at any moment (!),因此您的结果可能会有所不同。最好将 [desired/expected 时区][2] 明确指定为参数。

continent/region的格式指定proper time zone name,例如America/MontrealAfrica/CasablancaPacific/Auckland。切勿使用 ESTIST 等 2-4 字母缩写,因为它们 不是 真正的时区,未标准化,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

如果你想使用 JVM 当前的默认时区,请求它并作为参数传递。如果省略,则隐式应用 JVM 的当前默认值。最好是明确的,因为默认值可能会在任何时候 在运行时 中被 JVM 中任何应用程序的任何线程中的任何代码更改。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

比较

boolean isBeforeLimit = today.isBefore( limit ) ;  // Returns false.

关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time 类.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类.

在哪里获取java.time类?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.