Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript date to java.time.LocalDate

I'm trying to post json data to a Controller in Java.

This is my controller:

@ResponseBody
    @RequestMapping(value="/{schoolId}", method=RequestMethod.POST)
    public ClassGroupDTO addClassGroup(@RequestBody ClassGroupDTO classgroup, @PathVariable Integer schoolId) {
        return partyService.addClassGroup(classgroup, schoolId);
    }

This it the ClassGroupDTO

    public class ClassGroupDTO extends PartyDTO {
    private PartyDTO titular;
    private SiteDTO site;
    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate startDate;
    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate endDate;
...
}

I'm using Jackson 2.4.3.

I'm not able to post data when the field startDate or endDate is given. I've tried several formats to post. (I'm using moment.js)

data.startDate = moment().toDate();
data.startDate = moment().toJSON();
data.startDate = moment().format("YYYY/MM/DD");

Everytime I receive a Bad Request error. When I leave out startDate or endDate the data is posted and the controller is triggered.

How to deserialize javascript date to java.time.LocalDate?

like image 472
BakGat Avatar asked Oct 07 '14 10:10

BakGat


People also ask

Can we convert date to LocalDate in Java?

Date class and how that can be converted to a LocalDate as well. Starting with Java 8, we can find an additional toLocalDate() method on java. sql. Date, which also gives us an easy way of converting it to java.

How do I get time from LocaldateTime?

You can get the time from the LocaldateTime object using the toLocalTime() method. Therefore, another way to get the current time is to retrieve the current LocaldateTime object using the of() method of the same class. From this object get the time using the toLocalTime() method.

Does Java LocalDate have time?

A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03 . LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day.


1 Answers

I got the same problem, solved it using:

var dateString = new Date().toISOString().substring(0,10);

or

var dateString = new Date().toISOString().split("T")[0];

Convert to ISO string ("2015-10-14T09:39:49.942Z"), then keep only first ten characters ie, the date.

like image 51
jbigman Avatar answered Oct 17 '22 01:10

jbigman