converting date to string and back to date in java

前端 未结 5 2027
暗喜
暗喜 2020-12-21 23:14

In my program I am trying to convert the date to string to specified format and then back to date. I need the date to be in dd-MMM-yy format. So, I am converting the date to

5条回答
  •  没有蜡笔的小新
    2020-12-21 23:48

    We now have a more modern way to do this work.

    java.time

    The java.time framework is bundled with Java 8 and later. See Tutorial. These new classes are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. They are a vast improvement over the troublesome confusing old classes, java.util.Date/.Calendar et al.

    Date-only class

    The new framework offers a class, LocalDate, to represent a date-only without any time-of-day nor time zone.

    By the way, using two-digits for year is asking for trouble. I strongly recommend using four-digit years whenever possible. The java.time framework assumes any two-digit years are in the 20xx century, years 2000 to 2099 inclusive.

    To parse the string, specify the expected format. You are not using any of the standard ISO 8601 formats, so we must define a format pattern. Specify a Locale that includes the language we expect to find for name-of-month.

    // Parse String representation.
    String input = "23-May-12";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "d-MMMM-yy" , Locale.ENGLISH );  // Using four "M" characters means we expect the full name of the month.
    LocalDate localDate = formatter.parse ( input , LocalDate :: from );
    

    To go the other direction, to generate a string representation of the date value, we can recycle the same formatter.

        // Generate String representation.
        String output = localDate.format ( formatter );
    

    Dump to console.

        System.out.println ( "input: " + input + " → localDate : " + localDate );
        System.out.println ( "localDate : " + localDate + " → output: " + output );
    

    When run.

    input: 23-May-12 → localDate : 2012-05-23

    localDate : 2012-05-23 → output: 23-May-12

提交回复
热议问题