簡體   English   中英

如何將Calendar的時間與java.sql.Time對象進行比較?

[英]How to compare Calendar's time to java.sql.Time object?

我想知道Calendar對象的Time值是否等於java.sql.Time對象的值。

例如

Calendar c; //c.getTime().toString() == "Sat Jan 07 09:00:00 GMT 2012"
Time t;     //d.toString() == "09:00:00";

我試過了

t.equals(c.getTime())

但是因為日歷具有日期信息,所以表達式為false。

比較這兩者的最佳方法是什么?

編輯:
Time對象通過Hibernate檢索,並且沒有日期信息。

Calendar對象的創建者

Calendar c= Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 9);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);

您使用的方式非常好。 不過,目標尚不清楚。 為什么要讓c等於d

此外,沒有辦法使d.toString() == "09:00:00"Date始終包含所包含的日期。

不過,更重要的是Date沒有時區信息(以前曾經有,但是不鼓勵您觸摸Date這一部分),因此您無法從10:00 BST分辨出09:00 UTC – ,除非您指定時區。 您可以從Calendar c獲取時區,並且它說明了您需要執行的操作:

  1. 從您的日期創建Calendar
  2. 從您已經使用的日歷中復制時區
  3. 比較您感興趣的Calendar字段。 我想那將是小時,分鍾,秒,也許是毫秒。

更新:現在您已經提到它實際上是java.sql.Time ,我很擔心。 問題是,

  • SQL Server通常將時間存儲為包含小時,分鍾,秒等的結構。也就是說,存在隱式時區(SQL Server時區)
  • java.sql.Time存儲自1970年1月1日的“零紀元”值以來的時間(以毫秒為單位)。日期部分通常被剝離為1970年1月1日-但是此類不包含時區信息。 (同樣,它確實可以,但是已經過時了。)
  • Calendar具有明確設置的時區

實際上,這意味着使用系統默認時區將來自服務器的時間轉換為毫秒 ,然后讀取此值並將其與具有自己時區的Calendar進行比較。

如果聽起來令人困惑和脆弱,那是因為。 因此,基本上,您具有三個時區:

  1. SQL Server TZ
  2. JVM的默認TZ
  3. 日歷的TZ

所有這三個必須相同,以便進行任何比較都有意義。

您可以使用DateCalendarGregorianCalendar , SimpleDateFormat`等類在Java中處理日期時間。 讓我們看一些例子。

SimpleDateFormat dayFormat = new SimpleDateFormat("D");
int _currentDay = Integer.parseInt(dayFormat.format(new Date(System.currentTimeMillis())));

SimpleDateFormat monthFormat = new SimpleDateFormat("M");
int _currentMonth = Integer.parseInt(monthFormat.format(new Date(System.currentTimeMillis())));

SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
int _currentYear = Integer.parseInt(yearFormat.format(new Date(System.currentTimeMillis())));

System.out.println(_currentDay+"/"+_currentMonth+"/"+_currentYear);

將基於當前毫秒顯示當前日期。


String toDate = "07/1/2012";

DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
Calendar currentDateCal = Calendar.getInstance();

// Zero out the hour, minute, second, and millisecond.
currentDateCal.set(Calendar.HOUR_OF_DAY, 0);
currentDateCal.set(Calendar.MINUTE, 0);
currentDateCal.set(Calendar.SECOND, 0);
currentDateCal.set(Calendar.MILLISECOND, 0);

Date currentDate = currentDateCal.getTime();

Date toDt;

try
{
     toDt = df.parse(toDate);
}
catch (ParseException e)
{
     toDt = null;
     System.out.println(e.getMessage());
}

if (currentDate.equals(toDt))
{
     System.out.println(currentDate);  // Displays the current date.

     //Rest of the stuff.
}

String toDate = "07/12/2012";
try
{
     if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24)) 
     {
         System.out.println("True");
     }
     else
     {
         System.out.println("Untrue");
     }
}
catch(ParseException ex)
{
     Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

String toDateAsString = "07/12/2012";
Date toDate=null;

try
{
    toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);
}
catch (ParseException ex)
{
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;

if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime)
{
    System.out.println("True");
}
else
{
    System.out.println("False");
}

JodaTime的變體:

String toDateAsString = "07/01/2012";
DateTime toDate = DateTimeFormat.forPattern("MM/d/yyyy").parseDateTime(toDateAsString);
DateTime now = new DateTime();

if (!toDate.toLocalDate().isBefore(now.toLocalDate()))
{
    System.out.println("True");
} 
else
{
    System.out.println("False");
}

我今天必須這樣做,這篇文章中的答案幫助我解決了問題。 我知道我所有的時區都與OP相同。 而且我沒有在遺留代碼中使用Joda time的自由,因此為了使其他擁有相同條件的人受益,這就是我使用香草Java的方式。

方法:

  • 由於從java.util.Date繼承,所以java.sql.Time具有getTime() 使用此方法,可以創建一個java.util.Date對象,該對象僅表示自Java時代以來的時間部分。
  • 為了進行比較,必須將所需的java.util.Calendar對象轉換為一個java.util.Date對象,該對象表示自Java時代以來的另一時間。
  • 由於日期部分現在相等,因此兩個對象之間的任何比較都只會比較產生所需結果的時間部分。

沒有更多的理由,下面是代碼:

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Test {

    /**
     * Method to convert a calendar object to java's epoch date
     * keeping only the time information
     */
    public static Date toEpochDate(Calendar calendar) {
        return new Date(Time.valueOf(new SimpleDateFormat("HH:mm:ss").format(calendar.getTime())).getTime());
    }

    public static void main(String[] args) {

        // create any calendar object
        Calendar someTime = Calendar.getInstance();
        someTime.set(Calendar.HOUR_OF_DAY, 17);
        someTime.set(Calendar.MINUTE, 0);
        someTime.set(Calendar.SECOND, 0);

        // convert it to java epoch date
        Date someDate = toEpochDate(someTime);

        // create a date object from java.sql.Time
        Date fromSqlTime = new Date(Time.valueOf("17:00:00").getTime());

        // now do the comparison
        System.out.println("Some Date: " + someDate.toString());
        System.out.println("Sql Time: " + fromSqlTime.toString());
        System.out.println("Are they equal? " + someDate.equals(fromSqlTime));
    }
}

上面產生了以下輸出:

Some Date: Thu Jan 01 17:00:00 EST 1970
Sql Time: Thu Jan 01 17:00:00 EST 1970
Are they equal? true

使用以上方法,並將.equals()更改為.before().before() .after() ,可以創建各種時間比較方便的方法。

您為什么不比較時間以毫秒為單位?

Date d;
Calendar c;
System.out.println(d.getTime() == c.getTimeInMillis());

由於您用DateTime標記了這個問題,我假設您已經使用Joda

...
//Initialize Calendar and Date Object

DateTime d1 = new DateTime(c.getTime());
DateTime d2 = new DateTime(d.getTime());

// Convert d1 and d2 to LocalDate say ld1 and ld2 since, Java Date defaults to GMT

ld1.compareTo(ld2); 

暫無
暫無

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

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