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
.Letter | Description | Examples |
y | Year | 2013 |
M | Month in year | July, 07, 7 |
d | Day in month | 1-31 |
E | Day name in week | Friday, Sunday |
a | Am/pm marker | AM, PM |
H | Hour in day | 0-23 |
h | Hour in am/pm | 1-12 |
m | Minute in hour | 0-60 |
s | Second in minute | 0-60 |
Note
For complete date and time patterns, please refer to this java.text.SimpleDateFormat JavaDoc.
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