Convert Json date to java calendar

て烟熏妆下的殇ゞ 提交于 2019-12-04 01:53:01

问题


I have the following value /Date(1234043600000)/ in string type and I need to convert it to java calendar type without a success,I have tried to use the following post and create date and than do something like the post

How do I format a Microsoft JSON date?

Date date = new Date(parseInt(jsonDate.substr(6))); 

and than do someting like

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

I got error in the first line since in the word date i have line in the middle and substr(6) have error (The method substr(int) is undefined for the type String) ,how should I continue .

Thanks!


回答1:


This should work in Java

Date date = new Date(Long.parseLong(jsonDate.replaceAll(".*?(\\d+).*", "$1")));

the problem with your example is that it's only good for javascript




回答2:


The easiest way for you to get the number is to use

Long dateInMiliSeconds = new Scanner(jsonDate).nextLong();
Date date = new Date(dateInMiliSeconds);
Calendar cal = Calendar.getInstance();
cal.setTime(date);

Also the reason for your compilation error is that the method to get a sub string in Java String class is called subString not substr.

Although using the scanner is cleaner if you don't know much regex Evgeniy's answer may be better performance wise. I have no idea about the two approaches performance differences.



来源:https://stackoverflow.com/questions/18121082/convert-json-date-to-java-calendar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!