Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Would You Programmatically Create a Pattern from a Date that is Stored in a String?

Tags:

java

date

I have a string that contains the representation of a date. It looks like:

Thu Nov 30 19:00:00 EST 2006

I'm trying to create a Date object using SimpleDateFormat and have 2 problems.

1.) I can't figure out the pattern to hard-code the solution into the SimpleDateFormat constructor

2.) I can't find a way I could parse the string using API to determine the pattern so I could reuse this for different patterns of date output

If anyone knows a solution using API or a custom solution I would greatly appreciate it.

like image 589
Aaron Avatar asked Sep 04 '08 14:09

Aaron


3 Answers

The format to pass to SimpleDateFormat could be looked up at http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html

new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy")

As for your second question, I don't know of any Java library to figure out a date format and parse it without knowing in advance what the format is.

like image 146
Eli Courtwright Avatar answered Nov 14 '22 20:11

Eli Courtwright


The POJava date parser org.pojava.datetime.DateTime is an immutable, and robust parser that supports multiple languages, time zones, and formats.

Best of all, the parser is heuristic and does not require a pre-existing “format” to work. You just pass it a date/date-time text string and get out a java.util.Date!

like image 26
yinyueyouge Avatar answered Nov 14 '22 22:11

yinyueyouge


I'm not sure there's any easy way to parse a date and work out its pattern, but I would have thought that the pattern for the one you posted would be:

EEE MMM dd HH:mm:ss zzz yyyy

like image 28
alexmcchessers Avatar answered Nov 14 '22 20:11

alexmcchessers