How do I convert a String to a Date? Could you please provide a code sample?
Announcement
Collapse
No announcement yet.
X
-
Code://---------------------define an enum for date patterns public enum E1DateTimePattern { /** * pattern to format the date in dd/MM/yyyy */ PATTERN_1("dd/MM/yyyy"), /** * pattern to format the date in dd-MM-yyyy */ PATTERN_2("dd-MM-yyyy"); /** * date format pattern */ private String pattern = ""; /** * Constructor * * @param String * pattern for the formatter */ E1DateTimePattern(String format) { this.pattern = format; } @Override public String toString() { return String.valueOf(pattern); } } //-----------parse the string to date format private static Date parseDateTime(String str) throws ParseException { if (str == null) { throw new IllegalArgumentException("Date must not be null"); } E1DateTimePattern[] datePatterns = E1DateTimePattern.values(); Date dt = null; for (int i = 0; i < datePatterns.length; i++) { DateTimeFormat dtf = DateTimeFormat.getFormat(datePatterns[i] .toString()); try { dt = dtf.parse(str); break; } catch (Exception ex) { System.out.println("cannot parse in " + datePatterns[i].toString() + "format"); } } return dt; }
Last edited by Isomorphic; 9 Dec 2010, 20:30.
Comment
Comment