Geo Thomas
Geo Thomas

Reputation: 1159

How to pass java.util.date in REST urls using Jersey REST cleint

In my Java Spring MVC web application, I use Jersey REST client. I am trying to get some data by sending two Date objects to the server. But I am unable to use the Date objects in the urls. I am afraid if I convert them to string, I might not be able to get the exact timestamp in my server side. My url would be:

RESTDomain/siteid/{siteid}/pickupdate/{pickupdate}/returndate/{returndate}/pickuplocation/{pickuplocation}/returnlocation/{returnlocation}

So with data in them, it would look like:

/siteid/5/pickupdate/Thu Apr 14 00:00:00 IST 2016/returndate/Fri Apr 29 00:01:00 IST 2016/pickuplocation/1/returnlocation/1

And my controller would be :

@ResponseBody
@RequestMapping(
  value = "/siteid/{siteid}/pickupdate/{pickupdate}/returndate/{returndate}/pickuplocation/{pickuplocation}/returnlocation/{returnlocation}",
  method = RequestMethod.GET,
  headers = "Accept=application/json"
)
public CarDetailsListHB getDetails(
  @ModelAttribute("siteid") int siteId,
  @ModelAttribute("pickuplocation") int pickUpLocation,
  @ModelAttribute("returndate") Date returnDate,
  @ModelAttribute("pickupdate") Date pickupDate, 
  @ModelAttribute("returnlocation") int returnLocation,
  ModelMap model
) {
  //logic here
}

Is there any solution for this. Any help would be appreciated. Thanks

Upvotes: 1

Views: 1096

Answers (1)

S.B
S.B

Reputation: 688

You can pass it as a String and convert to the required format.Below code takes the String and returns the java.util.Date in the same format as the passed String. Check the below:

//your date as String
String date="Thu Apr 14 00:00:00 IST 2016";
            SimpleDateFormat dateformat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
            Date returnDate=dateformat.parse(date);//returnDate will have the Date object in same format.
            System.out.println(returnDate);

Your @ModelAttribute("returndate") String returnDate should be of String type. and in your controller method

SimpleDateFormat dateformat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
                Date newReturnDate=dateformat.parse(returnDate);//newReturnDate will have the Date object in same format.

For modifying the time part you can try the below:

Calendar cal = Calendar.getInstance();
            cal.setTime(newReturnDate);

            cal.set(Calendar.HOUR,11 );
            cal.set(Calendar.MINUTE,39 );   
            newReturnDate=cal.getTime();
            System.out.println(newReturnDate);

So newReturnDate will have the updated time.You would need to get the int values(hour and minute part) from your String "11:39".

Upvotes: 1

Related Questions