将 java.util.date 与 java.sql.Time 合并 [英] Merge java.util.date with java.sql.Time

查看:31
本文介绍了将 java.util.date 与 java.sql.Time 合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个广泛的 DATE-TIME 转换课程,但我遇到了一个我无法解决的场景:

I have an extensive DATE-TIME conversion class, but i came across a scenario that i cannot resolve:

我有一个 java.util.date:2011 年 5 月 10 日星期二 00:00:00 BST
我有一个 java.sql.time: 03:58:44

I have a java.util.date: Tue May 10 00:00:00 BST 2011
I have a java.sql.time: 03:58:44

我需要创建一个 java.util.date:Tue May 10 03:58:44 BST 2011

我想出的唯一方法是:

public static Date getDate(Date date, Time time) {
    Calendar calendar=Calendar.getInstance();
    calendar.set(date.getYear(), date.getMonth(), date.getDay(), time.getHours(), time.getMinutes(), time.getSeconds());
    return calendar.getTime();
}

完全弃用的代码,并且不起作用:java.lang.IllegalArgumentException at java.sql.Time.getYear(Unknown Source)

Totally deprecated code, and does not work: java.lang.IllegalArgumentException at java.sql.Time.getYear(Unknown Source)

有什么想法吗?

推荐答案

java.sql.Time 只是 java.util.Date 的包装器.您可以像添加两个 java.util.Date 对象一样使用它.

java.sql.Time is just a wrapper over the java.util.Date. You can use it as if you would add two java.util.Date objects.

例如将日历设置为 java.sql.Time:

For example, set Calendar to java.sql.Time:

calendar.setTime(time);

现在提取小时/分钟/秒字段,即:

Now extract the hour/minute/seconds fields, i.e.:

calendar.get(Calendar.HOUR);

接下来,将 Calendar 设置为 java.util.Date 对象并将这三个字段添加到其时间,即:

Next, set the Calendar to java.util.Date object and add these three fields to its time, i.e.:

calendar.add(Calendar.HOUR, hour);

并取回日期:

calendar.getTime();

这篇关于将 java.util.date 与 java.sql.Time 合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆