TOC
Java date stringindicates object of desire, like, hate, etc. java.util.Date Obtained by type
Java to convert a date string (in format yyyy/MM/dd ) to a java.util.Date The following is a sample program that converts to the
sample code
/** * Converts date string "yyyy/MM/dd" to java.util. Date type * @param str String to be converted * Date object after conversion. * @throws ParseException if date string is not "yyyy/MM/dd". *// public static Date toDate(String) public static Date toDate(String str) throws ParseException { Date date = DateFormat.getDateInstance().parse(str); return date; } }
Execution Result
sample program
public static void main(String[] args) { try { // Normal pattern Date date = toDate("2007/01/01"); System.out.println(date); // Pattern with different format date = toDate("2007-01-01"); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); } } }
output (result)
2007/01/01='Mon Jan 01 00:00:00 JST 2007'
The yyyy/MM/dd date string seems to have been converted correctly, but what about yyyy-MM-dd?
java.text.ParseException: Unparseable date: "2007-01-01" at java.text.DateFormat.parse(DateFormat.java:335) at Main.toDate(DateUtil.java:627) at Main.main(DateUtil.java:639)
ParseException was raised in yyyy-MM-dd.
DateFormat subclass of the SimpleDateFormat and write the following to convert it,
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); format.parse("2007-01-01");
I would like to see a more generic program.
Next, we will show you how to convert any date string to the java.util.
Convert any date/time string to Date or Calendar type.