Monday 14 July 2014

How To Convert String To Date – Java

In this tutorial, we will show you how to convert String to Date. Many Java beginners are stuck in the Date conversion, hope this summary guide will helps you in some ways.
Refer table below for some of the common date and time patterns used in java.text.SimpleDateFormat.
LetterDescriptionExamples
yYear2013
MMonth in yearJuly, 07, 7
dDay in month1-31
EDay name in weekFriday, Sunday
aAm/pm markerAM, PM
HHour in day0-23
hHour in am/pm1-12
mMinute in hour0-60
sSecond in minute0-60
Note
For complete date and time patterns, please refer to this java.text.SimpleDateFormat JavaDoc.

1. Date Example

If ‘M’ is 3 or more, then the month is interpreted as text, else number.
1. Date = 7-Jun-2013
 SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
 String dateInString = "7-Jun-2013";
 
 try {
 
  Date date = formatter.parse(dateInString);
  System.out.println(date);
  System.out.println(formatter.format(date));
 
 } catch (ParseException e) {
  e.printStackTrace();
 }
Output
Fri Jun 07 00:00:00 MYT 2013
07-Jun-2013
2. Date = 07/06/2013
 SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
 String dateInString = "07/06/2013";
 
 try {
 
  Date date = formatter.parse(dateInString);
  System.out.println(date);
  System.out.println(formatter.format(date));
 
 } catch (ParseException e) {
  e.printStackTrace();
 }
Output
Fri Jun 07 00:00:00 MYT 2013
07/06/2013
3. Date = Jun 7, 2013
 SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy");
 String dateInString = "Jun 7, 2013";  
 
 try {
 
  Date date = formatter.parse(dateInString);
  System.out.println(date);
  System.out.println(formatter.format(date));
 
 } catch (ParseException e) {
  e.printStackTrace();
 }
Output
Fri Jun 07 00:00:00 MYT 2013
Jun 07, 2013
4. Date = Fri, June 7 2013
 SimpleDateFormat formatter = new SimpleDateFormat("E, MMM dd yyyy");
 String dateInString = "Fri, June 7 2013";  
 
 try {
 
  Date date = formatter.parse(dateInString);
  System.out.println(date);
  System.out.println(formatter.format(date));
 
 } catch (ParseException e) {
  e.printStackTrace();
 }
Output
Fri Jun 07 00:00:00 MYT 2013
Fri, Jun 07 2013

2. Date and Time Example

1. Date and Time = Friday, Jun 7, 2013 12:10:56 PM
 SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
 String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";  
 
 try {
 
  Date date = formatter.parse(dateInString);
  System.out.println(date);
  System.out.println(formatter.format(date));
 
 } catch (ParseException e) {
  e.printStackTrace();
 }
Output
Fri Jun 07 12:10:56 MYT 2013
Friday, Jun 07, 2013 12:10:56 PM

No comments:

Post a Comment