簡體   English   中英

手動比較日期Java

[英]Comparing dates manually Java

我想比較一個字符串或參數,參數和參數,或類中的字符串和字符串中的兩個日期,而不使用SimpleDateFormat或Date庫以及測試。 我已經設置並測試了我的構造函數和獲取方法。

這就是我的偽代碼。

public static void compare(int d, int m, int y)

If year in c1 is greater than c2, print c2 is earlier than c1
Else if month in c1 is greater than c2, print c2 is earlier than c1
Else if day in c1 is greater than c2, print c2 is earlier than c1

我不確定在日期的每個部分都已經分開時如何比較兩個示例。 我有一個字符串方法,它將輸入作為字符串進行解析。 同樣,該方法應該在另一個程序中調用,在使用兩個變量的情況下,我將如何調用該方法?

您可以嘗試將日期轉換為“自01-01-0000起的天數”(或unix時間戳 )。 第一個適用於所有日期,第二個僅適用於1970年1月1日至2038年1月19日 (在32位系統上)。

由於這些值是可比較的數字,因此只需使用if塊並進行比較。

這是一個例子:

public int dateCompare(Date date1, Date date2) {

    if (date1.getYear() != date2.getYear())
        return (date1.getYear() - date2.getYear());
    if (date1.getMonth() != date2.getMonth())
        return (date1.getMonth() - date2.getMonth());
    return (date1.getDay() - date2.getDay());

}

輸出:

  • <0,如果date1 <date2
  • 如果date1 = date2 = = 0
  • 如果date1> date2> 0

如果您已經將日期分為年月日

擴展您的方法,這只是人工和勞動密集型檢查的一個示例

public static void compare(int firstDateDay, int firstDateMonth, int firstDateYear, int secondDateDay, int secondDateMonth, int secondDateYear)
{
   if (firstDateYear > secondDateYear)
   {
    // print secondDate is before first date 
   }
   else if (firstDateYear < secondDateYear )
   {
     // print secondDate is after first date 
   }
   else
  {
    // now check months 
  } 
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM