Trouble with Date & Calendar?

H

harry

I want to create a Date object that will always represent tomorrow @ 04:00am
but am a bit confused on the easiest way to do this?

So if now = 7th June, 2006 @ 18:30:00 I want to create a Date object for the
8th June, 2006 @ 04:00:00 if you see what I mean?

thanks in advance

harry
 
S

saimatam

import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
* Code to illustrate adding a DAY and setting fixed hour
* and minute.
*
* @author Sai Matam (saimatam at yahoo dot com )
*
*/

public class NextDay4Main
{
public static SimpleDateFormat
sdf = new SimpleDateFormat("MM/dd/yy HH:mm:ss");

public static void main(String[] args)
{
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
System.out.println(" Current date is: " + formatDate(cal.getTime()));
cal.add(Calendar.DAY_OF_YEAR, 1);
cal.set(Calendar.HOUR_OF_DAY, 4);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
System.out.println("Required date is: " + formatDate(cal.getTime()));
}

public static String formatDate(Date inDate)
{
StringBuffer buf = new StringBuffer(1024);
sdf.format(inDate, buf, new FieldPosition(0) );
return buf.toString();
}
}
 
M

Matt Humphrey

harry said:
I want to create a Date object that will always represent tomorrow @
04:00am
but am a bit confused on the easiest way to do this?

So if now = 7th June, 2006 @ 18:30:00 I want to create a Date object for
the
8th June, 2006 @ 04:00:00 if you see what I mean?

thanks in advance

What you want to do is to get the current date, roll the day over to the
next day and then set the timestamp to your time. Something like this:

public class Anon1 {
static SimpleDateFormat sdf = new SimpleDateFormat ("MM-dd-yyyy
HH:mm:ss.SSSS");

public static final void main (String [] args) {
Calendar cal = GregorianCalendar.getInstance ();
System.out.println(sdf.format(cal.getTime()));

cal.add(Calendar.DATE, 1);

cal.set(Calendar.HOUR_OF_DAY, 4);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND,0);

System.out.println (sdf.format(cal.getTime()));
}
}

Cheers,
Matt Humphrey (e-mail address removed) http://www.iviz.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top