如何将java.util.Date实例的时间设置为00:00:00? [英] How to set time of java.util.Date instance to 00:00:00?
问题描述
我有一个类型为 java.util.Date
的变量。
I have a variable of the type java.util.Date
.
如何设置时间部分到00:00:00?
How can I set the time part to 00:00:00?
我不允许使用Apache Commons库或JodaTime。 java.util.Calendar
可能是我唯一的选择。
I am not allowed to use an Apache Commons library or JodaTime. The java.util.Calendar
is probably my only option.
推荐答案
要完全删除 Date
对象中的时间,可以使用以下方法:
To remove time from the Date
object completely, you could use this:
public static Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
将 Date $ c传递到方法中$ c>您要修改的对象,它将返回没有小时/分钟等的
Date
。
Pass into the method the Date
object that you want to modify and it will return a Date
that has no hours/minutes etc.
如果不需要更改Date对象本身,请使用 SimpleDateFormat
。以您想要的方式设置格式,即。删除小时/分钟。然后调用format方法并传递要更改的 Date
对象。
If changing the Date object itself isn't required, use SimpleDateFormat
. Set the format the way you want ie. remove hours/minutes. Then call the format method and pass in the Date
object you want changed.
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy");
System.out.println(sdf.format(yourDate));
这篇关于如何将java.util.Date实例的时间设置为00:00:00?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!