How to set time to a date object in java

后端 未结 4 862
长情又很酷
长情又很酷 2020-12-07 14:27

I created a Date object in Java. When I do so, it shows something like: date=Tue Aug 09 00:00:00 IST 2011. As a result, it appears that my Excel fi

4条回答
  •  甜味超标
    2020-12-07 15:09

    If you don't have access to java 8 and the API java.time, here is my simple function to copy the time of one date to another date using the old java.util.Calendar (inspire by Jigar Joshi) :

    /**
     * Copy only the time of one date to the date of another date.
     */
    public static Date copyTimeToDate(Date date, Date time) {
        Calendar t = Calendar.getInstance();
        t.setTime(time);
    
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, t.get(Calendar.HOUR_OF_DAY));
        c.set(Calendar.MINUTE, t.get(Calendar.MINUTE));
        c.set(Calendar.SECOND, t.get(Calendar.SECOND));
        c.set(Calendar.MILLISECOND, t.get(Calendar.MILLISECOND));
        return c.getTime();
    }
    

提交回复
热议问题