Java Timestamp Example With Different Formats

Java 8 Date Parsing and Formatting with Examples

1. Overview

  • The temporal-based classes in the Date-Time API provide parse methods for parsing a string that contains date and time information. These classes also provide format methods for formatting temporal-based objects for display. In both cases, the process is similar: you provide a pattern to the DateTimeFormatter to create a formatter object. This formatter is then passed to the parse or format method.
  • The parse and the format methods throw an exception if a problem occurs during the conversion process. Therefore, your parse code should catch the DateTimeParseException error and your format code should catch the DateTimeException error. For more information on exception handing, see Catching and Handling Exceptions.

The DateTimeFormatter class provides numerous predefined formatters, or you can define your own.
Let's use few of the predefined formatters in our examples. Examples of this guide are available on Github.

2. Parsing

The one-argument parse(CharSequence) method in the LocalDate class uses the ISO_LOCAL_DATE formatter. To specify a different formatter, you can use the two-argument parse(CharSequence, DateTimeFormatter) method.
The following example uses the predefined BASIC_ISO_DATE formatter, which uses the format 19590709 for July 9, 1959.

            String in = ...; LocalDate date = LocalDate.parse(in, DateTimeFormatter.BASIC_ISO_DATE);          

2.1 LocalDate Class Formatting and Parsing Example

                package                com.ramesh.java8.datetime;                import                java.time.LocalDate;                import                java.time.format.DateTimeFormatter;                public                class                LocalDateFormat                {                private                static                final                DateTimeFormatter                formatter                =                DateTimeFormatter                .ofPattern(                  "d/MM/yyyy"                );                private                static                final                DateTimeFormatter                formatter1                =                DateTimeFormatter                .ofPattern(                  "d-MMM-yyyy"                );                private                static                final                DateTimeFormatter                formatter2                =                DateTimeFormatter                .ofPattern(                  "d/MM/yyyy"                );                public                static                void                main(String[]                args) {                                  //default format                System                .out.println(                  "Default format of LocalDate =                  "                                +                LocalDate                .now());                                  //                  The ISO date formatter that formats or parses a date without an                                  //                  offset, such as '20111203'                LocalDate                date                =                LocalDate                .now();                System                .out.println(date.format(DateTimeFormatter                                  .BASIC_ISO_DATE));                System                .out.println(date.format(DateTimeFormatter                                  .ISO_DATE));                System                .out.println(formatter.format(LocalDate                .parse(                  "16/08/2016"                , formatter)));                System                .out.println(formatter1.format(LocalDate                .parse(                  "16-Aug-2016"                , formatter1)));                System                .out.println(formatter2.format(LocalDate                .parse(                  "16/08/2016"                , formatter2))); } }

Output:

              Default format of LocalDate = 2018-07-11 20180711 2018-07-11 16/08/2016 16-Aug-2016 16/08/2016            

3. Formatting

The format(DateTimeFormatter) method converts a temporal-based object to a string representation using the specified format.

3.1 ZonedDateTime Class Formatting with Flight example

The followingFlight example, converts an instance of ZonedDateTime using the format "MMM d yyy hh:mm a". The date is defined in the same manner as was used for the previous parsing example, but this pattern also includes the hour, minutes, and a.m. and p.m. components.

              package              com.ramesh.java8.datetime;              import              java.time.DateTimeException;              import              java.time.LocalDateTime;              import              java.time.Month;              import              java.time.ZoneId;              import              java.time.ZonedDateTime;              import              java.time.format.DateTimeFormatter;              /*                              * This example uses ZonedDateTime to calculate the arrival time of                              * a flight that leaves from San Francisco and arrives in Tokyo.                              * The flight is 10 hours, 50 minutes long. Formatters are used to                              * print the departure and arrival times.                              */                            public              class              FlightZoneDateTimeExample              {              public              static              void              main(String[]              args) {              DateTimeFormatter              format              =              DateTimeFormatter              .ofPattern(                "MMM d yyyy  hh:mm a"              );                              //                Leaving from San Francisco on July 20, 2013, at 7:30 p.m.              LocalDateTime              leaving              =              LocalDateTime              .of(2013,              Month                              .JULY,              20,              19,              30);              ZoneId              leavingZone              =              ZoneId              .of(                "America/Los_Angeles"              );              ZonedDateTime              departure              =              ZonedDateTime              .of(leaving, leavingZone);              try              {              String              out1              =              departure.format(format);              System              .out.printf(                "LEAVING:  %s (%s)%n"              , out1, leavingZone);         }              catch              (DateTimeException              exc) {              System              .out.printf(                "%s can't be formatted!%n"              , departure);              throw              exc;         }                              //                Flight is 10 hours and 50 minutes, or 650 minutes              ZoneId              arrivingZone              =              ZoneId              .of(                "Asia/Tokyo"              );              ZonedDateTime              arrival              =              departure.withZoneSameInstant(arrivingZone)                                          .plusMinutes(650);              try              {              String              out2              =              arrival.format(format);              System              .out.printf(                "ARRIVING: %s (%s)%n"              , out2, arrivingZone);         }              catch              (DateTimeException              exc) {              System              .out.printf(                "%s can't be formatted!%n"              , arrival);              throw              exc;         }              if              (arrivingZone.getRules().isDaylightSavings(arrival.toInstant()))              System              .out.printf(                "                (%s daylight saving time will be in effect.)%n"              ,                               arrivingZone);              else              System              .out.printf(                "                (%s standard time will be in effect.)%n"              ,                               arrivingZone);     } }

Output:

            LEAVING:  Jul 20 2013  07:30 PM (America/Los_Angeles) ARRIVING: Jul 21 2013  10:20 PM (Asia/Tokyo)   (Asia/Tokyo standard time will be in effect.)          

3.2LocalDateTime Class Formatting and Parsing Example

              package              com.ramesh.java8.datetime;              import              java.time.Instant;              import              java.time.LocalDateTime;              import              java.time.format.DateTimeFormatter;              public              class              LocalDateTimeFormat              {              public              static              void              main(String[]              args) {              LocalDateTime              dateTime              =              LocalDateTime              .now();                              //default format              System              .out.println(                "Default format of LocalDateTime="                            +dateTime);                              //specific format              System              .out.println(dateTime.format(DateTimeFormatter              .ofPattern(                "d::MMM::uuuu HH::mm::ss"              )));              System              .out.println(dateTime.format(DateTimeFormatter                              .BASIC_ISO_DATE));              Instant              timestamp              =              Instant              .now();                              //default format              System              .out.println(                "Default format of Instant="                            +timestamp);                              //Parse examples              LocalDateTime              dt              =              LocalDateTime              .parse(                "27::Apr::2014 21::39::48"              ,              DateTimeFormatter              .ofPattern(                "d::MMM::uuuu HH::mm::ss"              ));              System              .out.println(                "Default format after parsing =                "                            +dt);  } }

Output:

            Default format of LocalDateTime=2018-07-11T16:24:57.130 11::Jul::2018 16::24::57 20180711 Default format of Instant=2018-07-11T10:54:57.179Z Default format after parsing = 2014-04-27T21:39:48          

5. Reference

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

overtonfelonfuld.blogspot.com

Source: https://www.javaguides.net/2018/07/java-8-date-parsing-and-formatting-with-examples.html

0 Response to "Java Timestamp Example With Different Formats"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel