如何将Calendar的时间与java.sql.Time对象进行比较?

时间:2012-01-07 17:28:32

标签: java datetime date calendar

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

E.g

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

我试过

t.equals(c.getTime())

但是因为Calendar有Date信息,所以表达式为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);

5 个答案:

答案 0 :(得分:2)

你使用的方式非常好。但目标尚不清楚。为什么您希望c等于d

此外,没有办法d.toString() == "09:00:00" - Date总是包含日期。

更重要的是,Date没有时区信息(好吧,它曾经有过,但你不鼓励接触Date的这一部分),所以你不能告诉{来自09:00 UTC的{​​1}} - 也就是说,除非您指定时区。您可以从10:00 BST获取时区,它可以解释您需要做什么:

  1. 从您的日期创建Calendar c
  2. 从您已使用的日历中复制时区
  3. 比较您感兴趣的Calendar字段。我想这将是小时,分钟,秒,也许是毫秒。
  4. 更新:现在你提到它实际上是Calendar,我很担心。问题是,

    • SQL服务器通常将时间存储为包含小时,分钟,秒等的结构。也就是说,存在隐含的时区(SQL Server时区)
    • java.sql.Time存储自1970年1月1日“零纪元”值以来的毫秒时间。日期部分通常被剥离到1970年1月1日 - 但此类不包含时区信息。 (好吧,再说一遍,但它被弃用了。)
    • java.sql.Time有明确设置的时区

    在实践中意味着,来自服务器gets converted into milliseconds using system default timezone的时间,然后您读取此值并将其与具有自己时区的Calendar进行比较。

    如果听起来令人困惑和脆弱,那是因为它是。所以基本上你有三个时区:

    1. SQL Server TZ
    2. JVM的默认TZ
    3. 日历的TZ
    4. 所有三个都必须相同,以便任何比较都有意义。

答案 1 :(得分:1)

您可以使用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");
}

答案 2 :(得分:0)

为什么不用毫秒来比较时间?

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

答案 3 :(得分:0)

因为你用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); 

答案 4 :(得分:0)

今天我必须这样做,这篇文章中的答案帮助我解决了我的问题。我知道我所有的时区都和OP一样。而且我没有时间在我的遗留代码中使用Joda时间,所以为了其他具有相同条件的人的利益,这就是我使用vanilla Java的方式。

方法:

  • java.sql.Time由于继承而有getTime() java.util.Date。使用这种方法,可以创建一个 java.util.Date对象,仅代表时间部分 Java纪元。
  • 为了进行比较,必须转换所需的java.util.Calendar object用于生成代表另一个的java.util.Date对象 自Java时代以来的时间。
  • 由于日期部分现在是等效的,所以2之间的任何比较 对象只会比较产生所需结果的时间部分。

如果没有进一步的说明,这里是代码:

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().after(),可以创建各种时间比较便利方法。