简体   繁体   English

将Javascript新日期转换为Java joda DateTime格式

[英]Convert Javascript new Date to Java joda DateTime format

I have an entity at my java backend which has a joda DateTime field called createdAt. 我在Java后端有一个实体,其中有一个joda DateTime字段,称为joda DateTime I have a post API to update these values on the Database. 我有一个发布API,可以更新数据库中的这些值。 The post API accepts application/json values . post API接受application/json values

I have an use case where in i need to make a Ajax POST request from my javascript file that updates the entity with the current date. 我有一个用例,其中我需要从我的JavaScript文件中发出一个Ajax POST请求,以当前日期更新实体。

Now that i need to pass a DateTime value in the POST data, i face a problem in converting the javascript Date object into joda DateTime . 现在,我需要在POST数据中传递DateTime值,因此在将javascript Date object转换为joda DateTime遇到问题。

I have tried sending the javascript Date object but it responds as : 我尝试发送javascript Date对象,但响应为:

Also Note: I cannot perform any actions on the data i receive from javascript before sending it to the repository on the java side. 另请注意:在将其从Java接收到的数据发送到Java端的存储库之前,我无法对其执行任何操作。

A bit late perhaps, but: 也许有点晚了,但是:

I had a similar problem. 我有一个类似的问题。 We use org.joda.time.LocalDate in our backend and passing a new Date() from javascript to the backend resulted in a conversion error. 我们在后端使用org.joda.time.LocalDate ,并将new Date()从javascript传递到后端导致转换错误。 We solved this by using new Date().valueOf() instead. 我们改用new Date().valueOf()解决了这一问题。 This will get the milliseconds since 1 jan 1970 (read about it at MDNs JavaScript Date page ). 自1970年1月1日起,这将是毫秒数(有关详细信息,请参见MDNs JavaScript Date页面 )。

After that you could just do org.joda.time.LocalDate.parse(passedInValue) 之后,您可以执行org.joda.time.LocalDate.parse(passedInValue)

This answer should help. 这个答案应该会有所帮助。 You will need to parse the String into a DateTime object 您将需要将String解析为DateTime对象

Objects cannot be "sent" in API calls. 无法在API调用中“发送”对象。 Objects are serialized(convert to string in this case) and deserialized(convert to appropriate object from string) 对象被序列化(在这种情况下转换为字符串)和反序列化(从字符串转换为适当的对象)

In this case: 在这种情况下:
- Serialization : Convert the Javascript Date object to appropriate format in a string before making the POST call - 序列化 :在进行POST调用之前,将Javascript Date对象转换为字符串中的适当格式
- Deserialize : Refer Converting a date string to a DateTime object using Joda Time library to convert the string into a DateTime object. - 反序列化 :请参阅使用Joda Time库日期字符串转换为DateTime对象,以将字符串转换为DateTime对象。

您可以将JavaScript new Date().toString()转换为字符串值并将其发布到服务器,然后可以使用SimpleDateFormat将其转换为Java服务器中的任何日期格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM