Link to home
Start Free TrialLog in
Avatar of kineticexpert
kineticexpertFlag for Australia

asked on

Convert Java Calendar to Date

Hi All,

I have a requirement to obtain the current date/time, and the date/time 5 mins from now. I can successfully do this using a Calendar, however the API that I am calling requires the times in teh Date datatype.

I think I could do it by setting the calendar to the proper times (which I am doing now - see below), but not sure on the best way to convert this to Date type?
Would I be best to pass the Calendar out as a string and then parse this into a date? Or use the milliseconds from the calendar to set the date?

Or is there an even easier way to this? Cheers
Calendar right_now = Calendar.getInstance();
        
        SimpleDateFormat formatter = new SimpleDateFormat("d-MMMM-yyyy hh:mm");
        System.out.println("Before Addition date is: " + formatter.format(right_now.getTime()));
        
        Calendar five_mins = Calendar.getInstance();
        five_mins.add(Calendar.MINUTE, 5);
       
         System.out.println("After Addition date is: " + formatter.format(five_mins.getTime()));

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of CPColin
CPColin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I think you can use the getTime() method as Colin said or return the long value of getTimeInMillis() and create a new Date object by
new Date(five_mins.getTimeInMillis())
right_now.getTime() returns the java.util.Date

right_now.getTime().getTime() returns the time in millisecons since epoch Jan 1, 1970.

Avatar of CEHJ
>>however the API that I am calling requires the times in teh Date datatype.

You can get the Date from the Calendar, of which you only need one instance:
        Calendar right_now = Calendar.getInstance();
 
        SimpleDateFormat formatter = new SimpleDateFormat("d-MMMM-yyyy hh:mm");
        System.out.println("Before Addition date is: " + formatter.format(right_now.getTime()));
 
        right_now.add(Calendar.MINUTE, 5);
        Date fiveMinsLater = right_now.getTime(); // Use this for method call
 
        System.out.println("After Addition date is: " + formatter.format(fiveMinsLater));

Open in new window

You can also do
Date d2 = new Date(System.currentTimeMillis() + (1000 * 60 * 5));

Open in new window

>          System.out.println("After Addition date is: " + formatter.format(five_mins.getTime()));

thats already passing a Date as others have mentioned above.
There is no need to change your code :)

Calendar nowCal = Calendar.getInstance();
nowCal.add(Calendar.MINUTE, 5);
Date d = new Date(nowCal.getTimeInMillis());