Convert string to date in java is popular case that we have to process in java projects. This tutorial shows you a complete example to demo this case and package this string to date conversion to utility function.
Here is complete program for converting string to date
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package com.javabycode.date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateExample { public static void main(String args[]) { String dateStr = "02/09/2016"; String dateStr2 = "02-09-2016 23:37:50"; String dateStr3 = "02-Sep-2016"; String dateStr4 = "09 02, 2016"; String dateStr5 = "Fri, Sep 02 2016"; String dateStr6 = "Fri, Sep 02 2016 23:37:50"; DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); DateFormat df2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); DateFormat df3 = new SimpleDateFormat("dd-MMM-yyyy"); DateFormat df4 = new SimpleDateFormat("MM dd, yyyy"); DateFormat df5 = new SimpleDateFormat("E, MMM dd yyyy"); DateFormat df6 = new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss"); try { // format() method formats a Date into a date/time string. Date d1 = df.parse(dateStr); System.out.println("Date: " + d1); System.out.println(" ==> Date in dd/MM/yyyy format is: " + df.format(d1)); Date d2 = df2.parse(dateStr2); System.out.println("Date: " + d2); System.out.println(" ==> Date in dd-MM-yyyy HH:mm:ss format is: " + df2.format(d2)); Date d3 = df3.parse(dateStr3); System.out.println("Date: " + d3); System.out.println(" ==> Date in dd-MMM-yyyy format is: " + df3.format(d3)); Date d4 = df4.parse(dateStr4); System.out.println("Date: " + d4); System.out.println(" ==> Date in MM dd, yyyy format is: " + df4.format(d4)); Date d5 = df5.parse(dateStr5); System.out.println("Date: " + d5); System.out.println(" ==> Date in E, MMM dd yyyy format is: " + df5.format(d5)); Date d6 = df6.parse(dateStr6); System.out.println("Date: " + d6); System.out.println(" ==> Date in E, E, MMM dd yyyy HH:mm:ss format is: " + df6.format(d6)); } catch (Exception ex) { System.out.println(ex); } } } |
Run above main and output will be printed like this:
For later use, you can package this string to date conversion to utility function. You need to declare a function with two string parameters and return a Date object. Here is the complete function code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<pre class="theme:eclipse lang:default decode:true " > /** * * @param dateStr Date string * @param format format string * @return */ public Date convertStringToDate(String dateStr, String format) { Date date = null; DateFormat df = new SimpleDateFormat(format); try { date = df.parse(dateStr); } catch (Exception ex) { System.out.println(ex); } return date; } |
That’s it on the tutorial Convert String to date in Java.