how can i set time value to 00:00:00 in the dateformat such as Tue Dec 28 17:36:28 IST 2010?
I'm using Java and I'm trying the below piece of code
Calendar cal1 = Calendar.getInstance();
cal.setTime(now1);
cal1.add(Calendar.DAY_OF_YEAR, -1);
java.util.Date yesterday =开发者_开发知识库 (Date) cal1.getTime();
System.out.println(yesterday.toString());
java.sql.Timestamp yesterdayTimestamp = new java.sql.Timestamp(tomorrow.getTime());
System.out.println(yesterdayTimestamp.toString());
which gives me the output as Tue Dec 28 17:36:28 IST 2010
Now I want to set the time in this to 00:00:00
then
Tue Dec 28 17:36:28 IST 2010
will be Tue Dec 28 00:00:00 IST 2010
I'm not getting how to do this?
If I have understand problem correctly you want to set time related fields to be set to 0.
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
cal1.set(Calendar.MILLISECOND, 0);
System.out.println(cal1.getTime());
Output
Wed Dec 29 00:00:00 IST 2010
You need to set the individual elements of the time component.
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#set(int, int)
cal1.set(Calendar.HOUR_OF_DAY, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
if you just need date , not time , you should use java.sql.Date.
In your calendar you can set the respective fields to 0: cal.set(Calendar.HOUR_OF_DAY, 0)
.
Alternatively, you can use joda-time, which has the DateMidnight
class for that purpose.
Btw, as noted in the comments - use a formatter. SimpleDateFormat
for example. You should not rely on the toString()
representation of an object.
精彩评论