Java如何做日历比较

时间:2018-10-12 11:39:48

标签: java date

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

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");
    }

4 个答案:

答案 0 :(得分:2)

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 );
}
  

     

am

     

     

     

加入

     

     

scholl

     

     

21/10/2108

提取最后一部分。

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及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendarSimpleDateFormat

目前位于Joda-Timemaintenance mode项目建议迁移到java.time类。

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

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

在哪里获取java.time类?

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

答案 1 :(得分:0)

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

    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),则应格外小心,因为它也可以毫秒精度工作,因此,如果允许用户将来输入时间值,则必须使用日期增量。

答案 2 :(得分:0)

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。

答案 3 :(得分:0)

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

CONTAINS(Name, N'"n*"'), CONTAINS(Name, N'"nn*"')

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

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

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

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

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

相关问题