java.text.SimpleDateFormat class is used to format and parse strings into dates and parse dates into strings.
One of the constructors of this class accepts a String value representing the desired date format and creates a SimpleDateFormat object. Parse/convert a string to a Date object
The following is a list of letters used for formatting with their descriptions and examples -
Letters |
Component |
Example |
Era Indicator | AD, BC | |
Year | 2005, 96 | |
Anniversary | 2005, 1996 | |
months of the year | September, September, 09 | |
一Months of the year | September, September, 09 | |
One Year Anniversary | 23 | |
| ||
p> Week of the month |
3 |
|
Day of the year |
129 |
##d |
Someday in January | 27 | ##F |
Day of the week | 5 | E |
Day of the week (name) | Monday, Monday | u |
Day of the week (number) | 1 | a |
AM/PM | Afternoon. AM | H |
Hour of day (0-23) | 0, 22 | ##k |
1, 12, 24 |
K | |
0, 5, 11 |
|
h | # Number of hours in ##am/pm (1-12)
1, 5, 12 | td>米 |
Minutes of the hour |
25 | s | Minutes and seconds | 24 | ##S |
Milliseconds |
756 | ##z | z |
Time Zone | ||
|
Z | Time zone |
X | Time Zone||
Example |
Live Demonstrationimport java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Sample { public static void main(String args[]) throws ParseException { SimpleDateFormat formatter = new SimpleDateFormat("yyyy/dd/MM"); Date date = formatter.parse("2007/25/06"); System.out.println("Date value: "+date); formatter = new SimpleDateFormat("y:G"); date = formatter.parse("1920:BC"); System.out.println("Date value: "+date); formatter = new SimpleDateFormat("D-M-Y"); date = formatter.parse("25-05-1989"); System.out.println("Date value: "+date); } } Copy after login Output |
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Sample { public static void main(String args[]) throws ParseException { SimpleDateFormat formatter1 = new SimpleDateFormat("HH:mm:ss"); Date time1 = formatter1.parse("07:25:30"); System.out.println("Date value: "+time1); SimpleDateFormat formatter2 = new SimpleDateFormat("EEE:MMM-d:YYYY"); Date time2 = formatter2.parse("Sun:Jan-8:2018"); System.out.println("Date value: "+time2); SimpleDateFormat formatter3 = new SimpleDateFormat("hh 'o''clock' a"); Date time3 = formatter3.parse("09 o'clock AM"); System.out.println("Date value: "+time3); } }
Date value: Thu Jan 01 07:25:30 IST 1970 Date value: Sun Dec 31 00:00:00 IST 2017 Date value: Thu Jan 01 09:00:00 IST 1970
The above is the detailed content of In Java, what is the SimpleDateFormat format code?. For more information, please follow other related articles on the PHP Chinese website!