簡體   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