繁体   English   中英

Java如何做日历比较

[英]Java how to do Calendar comparison

我从一个文本开始日期并存储在一个字符串变量中。 我想将该开始日期与当前日期进行比较,即开始日期早于当前日期。

public static void main(String[] rags) throws ParseException{
    String total= "I am Going to join in scholl at 21/10/2108";
    String[] effectiveDateText=total.split(" ");
    String effectiveDate=effectiveDateText[effectiveDateText.length-1];
    System.out.println(effectiveDate);
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Calendar today = Calendar.getInstance();
    String todate=sdf.format(today.getTime());
    System.out.println(todate);
    if(effectiveDate<todate){
        System.out.println("effective date is less then the previous date");
    }

tl; dr

使用现代的LocalDate类。

LocalDate.parse(                                       // Represent a date-only value without time-of-day and without time zone in `java.time.LocalDate` class.
        "I am Going to join in scholl at 21/10/2108".  // Split your input string, looking for last part separated by a SPACE.
        .substring( 
                "I am Going to join in scholl at 21/10/2108".lastIndexOf( " " ) 
                + 1                 
        ) 
        ,
        DateTimeFormatter.ofPattern( "dd/MM/uuuu" )    // Specify formatting pattern to match your input. Tip: Use ISO 8601 formats instead.
)
.toString()                                            // Generate text in standard ISO 8601 format.

2108-10-21

分割线

首先将字符串切成小段。

String input = "I am Going to join in scholl at 21/10/2108";
String[] parts = input.split( " " );

看那些部分。

for ( String part : parts ) {
    System.out.println( part );
}

一世

上午

要去

加入

cho

2108年10月21日

提取最后一部分。

String part = parts[ parts.length - 1 ]; // Subtract 1 for index (annoying zero-based counting).

LocalDate

现代方法使用java.time类。 具体来说, LocalDate用于仅包含日期的值,没有日期时间,没有时区或UTC偏移量。

将最后一部分解析为LocalDate 定义要匹配的格式模式。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( part , f );

ISO 8601

只要有可能,就不要使用旨在呈现给人类的格式在文本上交换日期时间值。

相反,请使用ISO 8601标准中为数据交换而定义的格式。 对于仅日期的值,它将是:YYYY-MM-DD

解析/生成文本时, java.time类默认使用ISO 8601格式。

String output = LocalDate.now().toString()

2018-01-23


关于java.time

java.time框架内置于Java 8及更高版本中。 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.DateCalendarSimpleDateFormat

现在处于维护模式Joda-Time项目建议迁移到java.time类。

要了解更多信息,请参见Oracle教程 并在Stack Overflow中搜索许多示例和说明。 规格为JSR 310

您可以直接与数据库交换java.time对象。 使用与JDBC 4.2或更高版本兼容的JDBC驱动程序 不需要字符串,不需要java.sql.*类。

在哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展了java.time。 该项目为将来可能在java.time中添加内容提供了一个试验场。 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

您应该将日期解析为Date格式,并使用提供的方法如下:

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    Date date1 = sdf.parse("21/10/2108");
    Date date2 = sdf.parse("20/01/2018");

    System.out.println("date1 : " + sdf.format(date1));
    System.out.println("date2 : " + sdf.format(date2));

    // after
    if (date1.after(date2)) {

    }
    // before
    if (date1.before(date2)) {

    }

很高兴知道:如果要使用date1.equals(date2),则应格外小心,因为它也可以毫秒级精度工作,因此,如果允许用户将来输入时间值,则必须使用日期增量。

Java Instant具有非常有用的方法来将两个即时进行比较,即isAfter()isBefore() 请参阅以下示例:

String total = "I am Going to join in scholl at 21/10/2018";
String[] effectiveDateText = total.split(" ");
String effectiveDate = effectiveDateText[effectiveDateText.length - 1];
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Instant joinDate = sdf.parse(effectiveDate).toInstant();
if (Instant.now().isAfter(joinDate)) {
    // ...
}

但是,您应该考虑时区。 例如,目前( Instant.now() )在世界上大多数地方是12/10/2018,但是在某些地方已经是13/10/2018(萨摩亚),在其他地方是11/10 / 2018(美国本土外小岛屿,仅剩一分钟)。

顺便说一句,我将21/10/2108更改为21/10/2018。

您可以使用此代码进行比较,

LocalDate currentDate = LocalDateTime.now().toLocalDate();
String cDate = ""+currentTime.getMonth().toString()+"/"+currentTime.getDayOfMonth().toString()+"/"+currentTime.getYear().toString();

现在cDate将具有日期字符串,格式为dd / MM / yyyy。 因此,为了进行比较,您可以使用Date类,

Date dOne = new SimpleDateFormat("dd/MM/yyyy").parse(cDate);
Date dTwo = new SimpleDateFormat("dd/MM/yyyy").parse(effectiveDate);

然后在两个日期上使用compareTo()方法,

dOne.compareTo(dTwo); // check value of this method

如果两个日期相同,则返回0,
如果小于0表示Date在参数日期之前,
如果大于0则表示Date在参数日期之后。

暂无
暂无

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

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