In this post, we will see how to convert String to Date object in java. It is used when we have formatted String and need to convert it to Date object.You may also check how to convert Date to String
Java program:
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 |
package org.arpit.java2blog; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class StringToDateExample { public static void main(String[] args) { String strDate1 = "25/01/2016"; String strDate2 = "25-Jan-2014"; String strDate3 = "Mon, Jan 25 2016"; /* * We will use SimpleDateFormat's parse method to convert String to date. */ try{ SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy"); // use parse method of SimpleDateFormat to convert it to date // Date object will be returned by parse method Date date1 = sdf1.parse(strDate1); System.out.println("Date in format dd/MM/yyyy " + sdf1.format(date1)); SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); Date date2 = sdf2.parse(strDate2); System.out.println("Date in format dd-MMM-yyyy: " + sdf2.format(date2)); SimpleDateFormat sdf3 = new SimpleDateFormat("E, MMM dd yyyy"); Date date3 = sdf3.parse(strDate3); System.out.println("Date in format E, MMM dd yyyy: " + sdf3.format(date3)); }catch(ParseException e){ // This exception will be thrown if string can not be converted to date System.out.println("Java String could not be converted to Date: " + e); } } } |
1 2 3 4 5 |
Date in format dd/MM/yyyy 25/01/2016 Date in format dd-MMM-yyyy: 25-Jan-2014 Date in format E, MMM dd yyyy: Mon, Jan 25 2016 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.