How to bind dateOfJoining value(String type) to member variable "dateOfJoining"(Date type) in "DateInput" Class after sending below JSON through postman. How to convert String to Date object in java with the same format dd/MM/yyyy. Converted date should be in Date object but not String.
Json is as given below
{
"dateOfJoining" : "03/04/2017"
}
Service URL hitting in postman -- localhost/Rest/hello
RestService class in java - HandleRestRequest.java
@RestController
public class HandleRestRequest
{
@RequestMapping("\hello");
public List setRequestParams(@RequestBody DateInput dateInput)
{
.......
}
}
Pojo Class DateInput.java
public class DateInput
{
private Date dateOfJoining;
.......
}
If I send date from json in below format, its throwing error as unsatisfied input
{
"dateOfJoining" : 04/04/2017
}
So I sending it as string format and by changing dateOfJoining as string in DateInput.java file and later I tried to convert it as date object as below
Modified DateInput.java file from Date to String
public class DateInput
{
private String dateOfJoining;
.......
}
Modified JSON
{
"dateOfJoining" : "04/04/2017"
}
Code to convert user input from String to Date
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String convertedDate = sdf.format(dateInput.getDateOfJoining());
Its converting into required format but return type is String but expected is Date object to send DAO layer. So I tried sdf.parse, its returning Date object but not in required format
Date date = sdf.parse(sdf.format(dateInput.getDateOfJoining()));
output is like - Tue Apr 04 00:00:00 IST 2017
expected is 04/04/2017 (with return type Date object).
So please help me how to convert the string to date object with required format since DAO layer is expecting input as date object in format dd/MM/yyyy
Edit: Updating answer in accordance with updated question.
Use annotation @JsonFormat
from Jackson Databind to specify the date pattern.
public class DateInput
{
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy")
private Date dateOfJoining;
.......
}
With JSON-B (included in Java EE 8) you can do this:
class DateInput {
@JsonbDateFormat("dd/MM/yyyy")
public Date dateOfJoining;
}
In my tests with Thorntail 2.4 I don't need any annotation for ISO format when using java.util.Date
:
{
"dateOfJoining" : "2019-04-28T14:45:15"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With