I am getting dates as strings from a web service.
They are in the following string format.
"2016-04-12 12:18:11.000 EDT"
The documentation is not very good but I guess this is some standard date format.
Do you recognize this format?
How can I most easily parse it into a Date
?
Asked
Active
Viewed 392 times
-7

peter.petrov
- 38,363
- 16
- 94
- 159
-
4Actually the documentation is really good, it even comes with a [tutorial](https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html) – Norsk Apr 13 '16 at 10:32
-
I meant the web service documentation. Wow, 4 downvotes... This is crazy. Thanks a bunch. People are really helpful in the SO Java tag. – peter.petrov Apr 13 '16 at 10:33
-
You have a gold badge in Java and don't know how to search for parsing String to Date? This is what I would call "Wow". – Tom Apr 13 '16 at 10:52
-
I guess the down-votes are from wondering which part of that string is confounding you. `2016` looks like a year. `04` and `12` are then obviously month and day. `12:18:11` sure looks like a time, and `.000` is millisecond. `EDT` is very likely US "Eastern Daylight Time". – Andreas Apr 13 '16 at 10:52
-
@Tom Forget about it. – peter.petrov Apr 13 '16 at 11:00
3 Answers
3
I think its either yyyy-MM-dd HH:mm:ss.SSS zzz
or yyyy-dd-MM HH:mm:ss.SSS zzz
from your example 2016-04-12,it can be 12th april,2016 or 4th december 2016
simple example by considering yyyy-MM-dd HH:mm:ss.SSS zzz
DateFormat gmtFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz");
TimeZone gmt = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmt);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date dd = df.parse("2016-04-12 12:18:11.000 EDT");
System.out.println( gmtFormat.format(dd));
output:2016-04-12 06:48:11.000 GMT

SpringLearner
- 13,738
- 20
- 78
- 116
2
You can do it like this:
String date = "2016-04-12 12:18:11.000 EDT";
DateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z", Locale.US);
Date d = parseFormat.parse(date);
Locale is important if your system is in a different language.

dambros
- 4,252
- 1
- 23
- 39
1
use this pattern:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
y Year (e.g. 12 or 2012). Use either yy or yyyy.
M Month in year. Number of M's determine length of format (e.g. MM, MMM or MMMMM)
d Day in month. Number of d's determine length of format (e.g. d or dd)
H Hour of day, 0-23 (normally HH)
m Minute in hour, 0-59 (normally mm)
s Second in minute, 0-59 (normally ss)
S Millisecond in second, 0-999 (normally SSS)
z Time Zone

Farvardin
- 5,336
- 5
- 33
- 54
-
Another answer suggests zzz instead of z (for time zone). What is the difference? – peter.petrov Apr 13 '16 at 10:55
-