作者:fuotb_204 | 来源:互联网 | 2023-01-15 09:30
IamtryingtowriteaREST-APIwithJersey.FromjavascriptIgetaDatestringlike:我正在尝试用Jersey编写
I am trying to write a REST-API with Jersey. From Javascript I get a Datestring like:
我正在尝试用Jersey编写REST-API。从Javascript我得到一个Datestring,如:
Tue Oct 16 2012 07:10:55 GMT+0200 (CEST)
(That's what
new Date().toString()
does, but this is not in my scope.)
是的,但这不在我的范围内。)
This date string can be parsed by implementing an own @ContextResolver. I been googling for about a day and the best SimpleDateFormat I could put together is:
可以通过实现自己的@ContextResolver来解析此日期字符串。我一直在谷歌搜索大约一天,我可以放在一起的最好的SimpleDateFormat是:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'z '('z')'", Locale.ROOT);
But as you can see the 'GMT'-part and the brackets are "hard-coded". Is there any better solution without changing the Javascript part?
但正如你可以看到'GMT'部分和括号是“硬编码”。没有更改Javascript部分有没有更好的解决方案?
2 个解决方案
0
@kidmenot: Thanks for the link, but that solution requires to handle the Javascript-date "manually" on the java side and to change the Javascript-side. So finally we needed to change the Javascript-part only. There was
@kidmenot:感谢您的链接,但该解决方案需要在Java端“手动”处理Javascript-date并更改Javascript端。所以最后我们只需要更改Javascript-part。有
var myDate = new Date():
// ... many LOCs
var myDateString = "" + myDate + "";
scattered all over the js-code. So just changing that to
分散在整个js-code中。所以只需改变它
var myDate = new Date():
// ... many LOCs
var myDateString = myDate;
solved the issue, because later on the was a
解决了这个问题,因为后来就是了
JSON.stringify()
just before sending it to the server. That JSON.stringify() calls myDate.toJSON() which returns an ISO-8601 datestring which gets processed by Jersey without the need for any further coding.
就在发送到服务器之前。 JSON.stringify()调用myDate.toJSON(),它返回一个ISO-8601日期字符串,由Jersey处理,无需任何进一步的编码。
So we chose this solution to spare us from future complications.
所以我们选择这个解决方案来避免将来的复杂化。
Edit half a year later:
半年后编辑:
This parse problem occured often and was finally inevitable because of some js-framework. The following is our Java-Solution:
这个解析问题经常发生,并且由于某些js框架而最终是不可避免的。以下是我们的Java解决方案:
public static Date jsDateStringToJavaDate(String jsDateString) throws ParseException{
String[] arrStrDateParts = jsDateString.split(" ");
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone(arrStrDateParts[5].substring(0,6)+":"+arrStrDateParts[5].substring(6)));
return sdf.parse(arrStrDateParts[0]+" "+arrStrDateParts[1]+" "+arrStrDateParts[2]+" "+arrStrDateParts[3]+" "+arrStrDateParts[4]);
}
If you got a better solution, please post it here. Thx
如果您有更好的解决方案,请在此处发布。谢谢