{"id":11,"date":"2007-03-18T16:03:56","date_gmt":"2007-03-18T21:03:56","guid":{"rendered":"http:\/\/wp.javatechniques.com\/blog\/dateformat-and-simpledateformat-examples\/"},"modified":"2007-06-25T12:48:46","modified_gmt":"2007-06-25T17:48:46","slug":"dateformat-and-simpledateformat-examples","status":"publish","type":"page","link":"http:\/\/javatechniques.com\/blog\/dateformat-and-simpledateformat-examples\/","title":{"rendered":"DateFormat and SimpleDateFormat Examples"},"content":{"rendered":"<p>Version 1.1 of Java introduced the <CODE>java.text<\/CODE> package, which included utility classes for parsing and formatting numbers and dates, along with utility classes for building other kinds of parsers.<\/p>\n<p><center><br \/>\n<script type=\"text\/javascript\"><!--\ngoogle_ad_client = \"pub-6996704245138669\";\ngoogle_ad_width = 468;\ngoogle_ad_height = 60;\ngoogle_ad_format = \"468x60_as\";\ngoogle_ad_type = \"text\";\ngoogle_ad_channel = \"\";\ngoogle_color_border = \"663300\";\ngoogle_color_bg = \"330000\";\ngoogle_color_link = \"FFFFFF\";\ngoogle_color_text = \"AECCEB\";\ngoogle_color_url = \"AECCEB\";\n\/\/-->\n<\/script><br \/>\n<script type=\"text\/javascript\"\n  src=\"http:\/\/pagead2.googlesyndication.com\/pagead\/show_ads.js\">\n<\/script><br \/>\n<\/center><\/p>\n<p><B>Default date formats<\/B><br \/>\n The <CODE>java.text.DateFormat<\/CODE> class, and its concrete subclass <CODE>java.text.SimpleDateFormat<\/CODE>, provide a convenient way to convert strings with date and\/or time info to and from <CODE>java.util.Date<\/CODE> objects. Figure 1 shows an example of using default <CODE>DateFormat<\/CODE> objects to format a date in a variety of ways:\n<\/td>\n<td><\/td>\n<\/tr>\n<\/table>\n<hr>\n<pre>\r\n\r\nimport java.text.DateFormat;\r\nimport java.util.Date;\r\n\r\npublic class DateFormatExample1 {\r\n\r\n    public static void main(String[] args) {\r\n        \/\/ Make a new Date object. It will be initialized to the current time.\r\n        Date now = new Date();\r\n\r\n        \/\/ See what toString() returns\r\n        System.out.println(\" 1. \" + now.toString());\r\n\r\n        \/\/ Next, try the default DateFormat\r\n        System.out.println(\" 2. \" + DateFormat.getInstance().format(now));\r\n\r\n        \/\/ And the default time and date-time DateFormats\r\n        System.out.println(\" 3. \" + DateFormat.getTimeInstance().format(now));\r\n        System.out.println(\" 4. \" + \r\n            DateFormat.getDateTimeInstance().format(now));\r\n\r\n        \/\/ Next, try the short, medium and long variants of the \r\n        \/\/ default time format \r\n        System.out.println(\" 5. \" + \r\n            DateFormat.getTimeInstance(DateFormat.SHORT).format(now));\r\n        System.out.println(\" 6. \" + \r\n            DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now));\r\n        System.out.println(\" 7. \" + \r\n            DateFormat.getTimeInstance(DateFormat.LONG).format(now));\r\n\r\n        \/\/ For the default date-time format, the length of both the\r\n        \/\/ date and time elements can be specified. Here are some examples:\r\n        System.out.println(\" 8. \" + DateFormat.getDateTimeInstance(\r\n            DateFormat.SHORT, DateFormat.SHORT).format(now));\r\n        System.out.println(\" 9. \" + DateFormat.getDateTimeInstance(\r\n            DateFormat.MEDIUM, DateFormat.SHORT).format(now));\r\n        System.out.println(\"10. \" + DateFormat.getDateTimeInstance(\r\n            DateFormat.LONG, DateFormat.LONG).format(now));\r\n    }\r\n}\r\n<\/pre>\n<p><HR><br \/>\n<CENTER>Figure 1. Using default <CODE>DateFormat<\/CODE> objects to format a <CODE>Date<\/CODE> object.<\/CENTER><\/p>\n<p>When you run this class, you will see output that looks something like that shown in Figure 2.<\/p>\n<p><HR><\/p>\n<pre>\r\n\r\n&gt; java DateFormatExample1\r\n 1. Tue Nov 04 20:14:11 EST 2003\r\n 2. 11\/4\/03 8:14 PM\r\n 3. 8:14:11 PM\r\n 4. Nov 4, 2003 8:14:11 PM\r\n 5. 8:14 PM\r\n 6. 8:14:11 PM\r\n 7. 8:14:11 PM EST\r\n 8. 11\/4\/03 8:14 PM\r\n 9. Nov 4, 2003 8:14 PM\r\n10. November 4, 2003 8:14:11 PM EST\r\n<\/pre>\n<p><HR><br \/>\n<CENTER>Figure 2. Output from example in Figure 1<\/CENTER><\/p>\n<p>Default <CODE>DateFormat<\/CODE> objects retrieved from the static <CODE>getInstance()<\/CODE>, <CODE>getTimeInstance()<\/CODE>, and <CODE>getDateTimeInstance()<\/CODE> methods can also be used for parsing <CODE>String<\/CODE> objects to produce <CODE>Date<\/CODE> objects. Figure 3 shows a simple example of this.<\/p>\n<p><HR><\/p>\n<pre>\r\n\r\nimport java.text.DateFormat;\r\nimport java.text.ParseException;\r\nimport java.util.Date;\r\n\r\npublic class DateFormatExample2 {\r\n\r\n    public static void main(String[] args) {\r\n        \/\/ Make a String that has a date in it, with MEDIUM date format\r\n        \/\/ and SHORT time format.\r\n        String dateString = \"Nov 4, 2003 8:14 PM\";\r\n\r\n        \/\/ Get the default MEDIUM\/SHORT DateFormat\r\n        DateFormat format = \r\n            DateFormat.getDateTimeInstance(\r\n            DateFormat.MEDIUM, DateFormat.SHORT);\r\n\r\n        \/\/ Parse the date\r\n        try {\r\n            Date date = format.parse(dateString);\r\n            System.out.println(\"Original string: \" + dateString);\r\n            System.out.println(\"Parsed date    : \" + \r\n                 date.toString());\r\n        }\r\n        catch(ParseException pe) {\r\n            System.out.println(\"ERROR: could not parse date in string \\\"\" +\r\n                dateString + \"\\\"\");\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p><HR><br \/>\n<CENTER>Figure 3. Using default <CODE>DateFormat<\/CODE> objects to parse a <CODE>String<\/CODE><\/CENTER><\/p>\n<p>The result is shown in Figure 4. Note that since the string version of the date did not contain timezone or seconds, the timezone is set to the default timezone (EST, in this case) and the seconds are set to zero.<\/p>\n<p><HR><\/p>\n<pre>\r\n\r\n&gt; java DateFormatExample2\r\nOriginal string: Nov 4, 2003 8:14 PM\r\nParsed date    : Tue Nov 04 20:14:00 EST 2003\r\n<\/pre>\n<p><HR><br \/>\n<CENTER>Figure 4. Parsing a date string<\/CENTER><\/p>\n<p>The <CODE>parse<\/CODE> method throws an exception if a date matching the format cannot be parsed. In the code shown in Figure 3, the string matches the format exactly. To see what happens when a bad string is encountered, the class in Figure 5 reads and attempts to parse input until a blank line (or a Control-D) is entered.<\/p>\n<p><HR><\/p>\n<pre>\r\n\r\nimport java.text.DateFormat;\r\nimport java.text.ParseException;\r\nimport java.util.Date;\r\nimport java.io.IOException;\r\nimport java.io.BufferedReader;\r\nimport java.io.InputStreamReader;\r\n\r\npublic class DateFormatExample3 {\r\n\r\n    public static void main(String[] args) {\r\n        \/\/ Get the default MEDIUM\/SHORT DateFormat\r\n        DateFormat format = \r\n            DateFormat.getDateTimeInstance(DateFormat.MEDIUM, \r\n            DateFormat.SHORT);\r\n\r\n        \/\/ Read and parse input, stopping on a blank input line\r\n        BufferedReader reader = \r\n            new BufferedReader(new InputStreamReader(System.in));\r\n        try {\r\n            System.out.print(\"ENTER DATE STRING: \");\r\n            String dateString = reader.readLine();\r\n\r\n            while ((dateString != null) && (dateString.length() > 0)) {\r\n                \/\/ Parse the date\r\n                try {\r\n                    Date date = format.parse(dateString);\r\n                    System.out.println(\"Original string: \" + dateString);\r\n                    System.out.println(\"Parsed date    : \" + \r\n                        date.toString());\r\n                    System.out.println(); \/\/ Skip a line\r\n                }\r\n                catch(ParseException pe) {\r\n                    System.out.println(\r\n                        \"ERROR: could not parse date in string \\\"\" +\r\n                        dateString + \"\\\"\");\r\n                }\r\n\r\n                \/\/ Read another string\r\n                System.out.print(\"ENTER DATE STRING: \");\r\n                dateString = reader.readLine();\r\n            }\r\n        }\r\n        catch(IOException ioe) {\r\n            System.out.println(\"I\/O Exception: \" + ioe);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p><HR><br \/>\n<CENTER>Figure 5. Example of parsing dates entered on the command line<\/CENTER><\/p>\n<p>Figure 6 shows an example of running this class and entering several date strings. (Text entered is shown in italics.)<\/p>\n<p><HR><\/p>\n<pre>\r\n\r\n&gt; java DateFormatExample3\r\nENTER DATE STRING: <I>Nov 4, 2003 8:14 PM<\/I>\r\nOriginal string: Nov 4, 2003 8:14 PM\r\nParsed date    : Tue Nov 04 20:14:00 EST 2003\r\n\r\n<FONT COLOR=red>ENTER DATE STRING: <I>Nov 4, 2003 8:14<\/I>\r\nERROR: could not parse date in string \"Nov 4, 2003 8:14 \"<\/FONT>\r\n\r\nENTER DATE STRING: <I>Nov 4, 2003 8:14 AM<\/I>\r\nOriginal string: Nov 4, 2003 8:14 AM\r\nParsed date    : Tue Nov 04 08:14:00 EST 2003\r\n\r\nENTER DATE STRING: <I>November 4, 2003 8:14 AM<\/I>\r\nOriginal string: November 4, 2003 8:14 AM\r\nParsed date    : Tue Nov 04 08:14:00 EST 2003\r\n\r\nENTER DATE STRING: <I>Nov 4, 2003 20:14 PM<\/I>\r\nOriginal string: Nov 4, 2003 20:14 PM\r\nParsed date    : Wed Nov 05 08:14:00 EST 2003\r\n\r\n<FONT COLOR=red>ENTER DATE STRING: <I>Nov 4, 2003 20:14<\/I>  \r\nERROR: could not parse date in string \"Nov 4, 2003 20:14\"<\/FONT>\r\n\r\nENTER DATE STRING: \r\n<\/pre>\n<p><HR><br \/>\n<CENTER>Figure 6. Parsing a variety of date strings<\/CENTER><\/p>\n<p>Note that the default parser is somewhat flexible. It recognizes a long version of the month name (&#8220;November&#8221; instead of &#8220;Nov&#8221;), but does not recognize the two dates shown in red, both of which are missing AM or PM. Furthermore, it produces possibly unexpected results when the time &#8220;20:14 PM&#8221; is entered: The parsed date is 8:14 the next morning.<\/p>\n<p><CODE>DateFormat<\/CODE> actually gives you a small amount of control over leniency in parsing. The default <CODE>DateFormat<\/CODE> instances are lenient by default, but invoking <CODE>format.setLenient(false);<\/CODE> in the example in Figure 5 would cause the &#8220;20:14 PM&#8221; example (in Figure 6) to fail, though it will still accept &#8220;November&#8221; or &#8220;Nov&#8221;.<\/p>\n<p><B>Using SimpleDateFormat for custom date formatting and parsing<\/B><\/p>\n<p>The default <CODE>DateFormat<\/CODE> instances returned by the static methods in the <CODE>DateFormat<\/CODE> class may be sufficient for many purposes, but clearly do not cover all possible valid or useful formats for dates. For example, notice that in Figure 2, none of the <CODE>DateFormat<\/CODE>-generated strings (numbers 2 &#8211; 9) match the format of the output of the <CODE>Date<\/CODE> class&#8217;s <CODE>toString()<\/CODE> method. This means that you cannot use the default <CODE>DateFormat<\/CODE> instances to parse the output of <CODE>toString()<\/CODE>, something that might be useful for things like parsing log data.<\/p>\n<p>The <CODE>SimpleDateFormat<\/CODE> lets you build custom formats. Dates are constructed with a string that specifies a pattern for the dates to be formatted and\/or parsed. From the <CODE>SimpleDateFormat<\/CODE> JavaDocs, the characters in Figure 7 can be used in date formats. Where appropriate, 4 or more of the character will be interpreted to mean that the long format of the element should be used, while fewer than 4 mean that a short format should be used.<br \/>\n<HR><br \/>\n<TABLE BORDER=\"0\" WIDTH=\"100%\" VALIGN=\"TOP\"><TR><TD><B>Symbol<\/B><\/TD><TD><B>Meaning<\/B><\/TD><TD><B>Type<\/B><\/TD><TD><B>Example<\/B><\/TD><\/TR><TR BGCOLOR=\"lightgrey\"><TD>G<\/TD><TD>Era<\/TD><TD>Text<\/TD><TD>&#8220;GG&#8221; -&gt; &#8220;AD&#8221;<\/TD><\/TR><TR><TD>y<\/TD><TD>Year<\/TD><TD>Number<\/TD><TD>&#8220;yy&#8221; -&gt; &#8220;03&#8221;<BR>&#8220;yyyy&#8221; -&gt; &#8220;2003&#8221;<\/TD><\/TR><TR BGCOLOR=\"lightgrey\"><TD>M<\/TD><TD>Month<\/TD><TD>Text or Number<\/TD><TD>&#8220;M&#8221; -&gt; &#8220;7&#8221;<BR>&#8220;M&#8221; -&gt; &#8220;12&#8221;<BR>&#8220;MM&#8221; -&gt; &#8220;07&#8221;<BR>&#8220;MMM&#8221; -&gt; &#8220;Jul&#8221;<BR>&#8220;MMMM&#8221; -&gt; &#8220;December&#8221;<\/TD><\/TR><TR><TD>d<\/TD><TD>Day in month<\/TD><TD>Number<\/TD><TD>&#8220;d&#8221; -&gt; &#8220;3&#8221;<BR>&#8220;dd&#8221; -&gt; &#8220;03&#8221;<\/TD><\/TR><TR BGCOLOR=\"lightgrey\"><TD>h<\/TD><TD>Hour (1-12, AM\/PM)<\/TD><TD>Number<\/TD><TD>&#8220;h&#8221; -&gt; &#8220;3&#8221;<BR>&#8220;hh&#8221; -&gt; &#8220;03&#8221;<\/TD><\/TR><TR><TD>H<\/TD><TD>Hour (0-23)<\/TD><TD>Number<\/TD><TD>&#8220;H&#8221; -&gt; &#8220;15&#8221;<BR>&#8220;HH&#8221; -&gt; &#8220;15&#8221;<\/TD><\/TR><TR BGCOLOR=\"lightgrey\"><TD>k<\/TD><TD>Hour (1-24)<\/TD><TD>Number<\/TD><TD>&#8220;k&#8221; -&gt; &#8220;3&#8221;<BR>&#8220;kk&#8221; -&gt; &#8220;03&#8221;<\/TD><\/TR><TR><TD>K<\/TD><TD>Hour (0-11 AM\/PM)<\/TD><TD>Number<\/TD><TD>&#8220;K&#8221; -&gt; &#8220;15&#8221;<BR>&#8220;KK&#8221; -&gt; &#8220;15&#8221;<\/TD><\/TR><TR BGCOLOR=\"lightgrey\"><TD>m<\/TD><TD>Minute<\/TD><TD>Number<\/TD><TD>&#8220;m&#8221; -&gt; &#8220;7&#8221;<BR>&#8220;m&#8221; -&gt; &#8220;15&#8221;<BR>&#8220;mm&#8221; -&gt; &#8220;15&#8221;<\/TD><\/TR><TR><TD>s<\/TD><TD>Second<\/TD><TD>Number<\/TD><TD>&#8220;s&#8221; -&gt; &#8220;15&#8221;<BR>&#8220;ss&#8221; -&gt; &#8220;15&#8221;<\/TD><\/TR><TR BGCOLOR=\"lightgrey\"><TD>S<\/TD><TD>Millisecond (0-999)<\/TD><TD>Number<\/TD><TD>&#8220;SSS&#8221; -&gt; &#8220;007&#8221;<\/TD><\/TR><TR><TD>E<\/TD><TD>Day in week<\/TD><TD>Text<\/TD><TD>&#8220;EEE&#8221; -&gt; &#8220;Tue&#8221;<BR>&#8220;EEEE&#8221; -&gt; &#8220;Tuesday&#8221;<\/TD><\/TR><TR BGCOLOR=\"lightgrey\"><TD>D<\/TD><TD>Day in year (1-365 or 1-364)<\/TD><TD>Number<\/TD><TD>&#8220;D&#8221; -&gt; &#8220;65&#8221;<BR>&#8220;DDD&#8221; -&gt; &#8220;065&#8221;<\/TD><\/TR><TR><TD>F<\/TD><TD>Day of week in month (1-5)<\/TD><TD>Number<\/TD><TD>&#8220;F&#8221; -&gt; &#8220;1&#8221;<\/TD><\/TR><TR BGCOLOR=\"lightgrey\"><TD>w<\/TD><TD>Week in year (1-53)<\/TD><TD>Number<\/TD><TD>&#8220;w&#8221; -&gt; &#8220;7&#8221;<\/TD><\/TR><TR><TD>W<\/TD><TD>Week in month (1-5)<\/TD><TD>Number<\/TD><TD>&#8220;W&#8221; -&gt; &#8220;3&#8221;<\/TD><\/TR><TR BGCOLOR=\"lightgrey\"><TD>a<\/TD><TD>AM\/PM<\/TD><TD>Text<\/TD><TD>&#8220;a&#8221; -&gt; &#8220;AM&#8221;<BR>&#8220;aa&#8221; -&gt; &#8220;AM&#8221;<\/TD><\/TR><TR><TD>z<\/TD><TD>Time zone<\/TD><TD>Text<\/TD><TD>&#8220;z&#8221; -&gt; &#8220;EST&#8221;<BR>&#8220;zzz&#8221; -&gt; &#8220;EST&#8221;<BR>&#8220;zzzz&#8221; -&gt; &#8220;Eastern Standard Time&#8221;<\/TD><\/TR><TR BGCOLOR=\"lightgrey\"><TD>&#8216;<\/TD><TD>Excape for text<\/TD><TD>Delimiter<\/TD><TD>&#8220;&#8216;hour&#8217; h&#8221; -&gt; &#8220;hour 9&#8221;<\/TD><\/TR><TR><TD>&#8221;<\/TD><TD>Single quote<\/TD><TD>Literal<\/TD><TD>&#8220;ss&#8221;SSS&#8221; -&gt; &#8220;45&#8217;876&#8221;<\/TD><\/TR><\/TABLE><\/p>\n<p><HR><br \/>\n<CENTER>Figure 7. Syntax elements for <CODE>SimpleDateFormat<\/CODE><\/CENTER><\/p>\n<p>Note that you will generally never want to use single-digit minutes, seconds, or milliseconds, even though these are supported by <CODE>SimpleDateFormat<\/CODE> (&#8220;m&#8221;, &#8220;s&#8221;, &#8220;S&#8221;).<\/p>\n<p>Using the syntax from Figure 7, we can now make a <CODE>SimpleDateFormat<\/CODE> that can read the output of <CODE>Date.toString()<\/CODE>. Figure 8 shows an example this:<br \/>\n<HR><\/p>\n<pre>\r\n\r\nimport java.text.DateFormat;\r\nimport java.text.SimpleDateFormat;\r\nimport java.text.ParseException;\r\nimport java.util.Date;\r\n\r\npublic class DateFormatExample4 {\r\n\r\n    public static void main(String[] args) {\r\n        \/\/ Make a new Date object. It will be initialized to the \r\n        \/\/ current time.\r\n        Date now = new Date();\r\n\r\n        \/\/ Print the result of toString()\r\n        String dateString = now.toString();\r\n        System.out.println(\" 1. \" + dateString);\r\n\r\n        \/\/ Make a SimpleDateFormat for toString()'s output. This\r\n        \/\/ has short (text) date, a space, short (text) month, a space,\r\n        \/\/ 2-digit date, a space, hour (0-23), minute, second, a space,\r\n        \/\/ short timezone, a final space, and a long year.\r\n        SimpleDateFormat format = \r\n            new SimpleDateFormat(\"EEE MMM dd HH:mm:ss zzz yyyy\");\r\n\r\n        \/\/ See if we can parse the output of Date.toString()\r\n        try {\r\n            Date parsed = format.parse(dateString);\r\n            System.out.println(\" 2. \" + parsed.toString());\r\n        }\r\n        catch(ParseException pe) {\r\n            System.out.println(\"ERROR: Cannot parse \\\"\" + dateString + \"\\\"\");\r\n        }\r\n\r\n        \/\/ Print the result of formatting the now Date to see if the result\r\n        \/\/ is the same as the output of toString()\r\n        System.out.println(\" 3. \" + format.format(now));\r\n    }\r\n}\r\n<\/pre>\n<p>The output shows three identical strings:<\/p>\n<pre>\r\n\r\n&gt; java DateFormatExample4\r\n 1. Tue Nov 04 21:53:43 EST 2003\r\n 2. Tue Nov 04 21:53:43 EST 2003\r\n 3. Tue Nov 04 21:53:43 EST 2003\r\n<\/pre>\n<p><HR><br \/>\n<CENTER>Figure 8. A parser for <CODE>Date.toString()<\/CODE> output<\/CENTER><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Version 1.1 of Java introduced the java.text package, which included utility classes for parsing and formatting numbers and dates, along with utility classes for building other kinds of parsers. Default date formats The java.text.DateFormat class, and its concrete subclass java.text.SimpleDateFormat, provide a convenient way to convert strings with date and\/or time info to and from &hellip; <\/p>\n<p class=\"link-more\"><a href=\"http:\/\/javatechniques.com\/blog\/dateformat-and-simpledateformat-examples\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;DateFormat and SimpleDateFormat Examples&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"open","template":"","meta":{"footnotes":""},"class_list":["post-11","page","type-page","status-publish","hentry","entry"],"_links":{"self":[{"href":"http:\/\/javatechniques.com\/blog\/wp-json\/wp\/v2\/pages\/11","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/javatechniques.com\/blog\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"http:\/\/javatechniques.com\/blog\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"http:\/\/javatechniques.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/javatechniques.com\/blog\/wp-json\/wp\/v2\/comments?post=11"}],"version-history":[{"count":0,"href":"http:\/\/javatechniques.com\/blog\/wp-json\/wp\/v2\/pages\/11\/revisions"}],"wp:attachment":[{"href":"http:\/\/javatechniques.com\/blog\/wp-json\/wp\/v2\/media?parent=11"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}