问题
I have a string that represents a date. I do not know the date format of the string. But for example only, it may be any of
- 2015-10-14T16:41:42.000Z
- 2015-10-14T19:01:53.100+01:00
- 2015-10-14 05:20:29
or any valid format that a website may use to describe date in a meta tag (so the format will be official, as opposed to whimsical, but the set of possibilities is not small).
Can I use joda-time to solve this issue? How about java.util.Date
or anything else?
update
I think I find a Javascript equivalent of what I am looking for
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
But I need an answer for Java.
回答1:
well this is not a real "java" solution, but if you have found a Javascript one, than you can use the Javascript solution in java using the ScriptEngine.
just a little quick and dirty... :)
here is a sample code:
public static void main(String[] args) throws ScriptException, ParseException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
String[] dateStrings = new String[] {
"2015-10-14T16:41:42.000Z",
"2015-10-14T19:01:53.100+01:00",
"2015-10-14 05:20:29" };
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
for (String d : dateStrings) {
String script = "new Date('" + d + "')";
Object eval = engine.eval(script);
Date parsed = sdf.parse(eval.toString().replace("[Date ", "").replace("]", ""));
System.out.println(eval + " -> " + parsed);
}
}
that prints out:
[Date 2015-10-14T16:41:42.000Z] -> Wed Oct 14 18:41:42 CEST 2015
[Date 2015-10-14T18:01:53.100Z] -> Wed Oct 14 20:01:53 CEST 2015
[Date 2015-10-14T03:20:29.000Z] -> Wed Oct 14 05:20:29 CEST 2015
The eval.toString() part can be improved obviously. as the locale settings...
来源:https://stackoverflow.com/questions/33134422/converting-string-representation-of-unknown-date-format-to-date-in-java