简体   繁体   中英

How to parse the date for February and months with 31 days?

I thank you for possible answers. The problem is, I work with a legacy system with Java 1.4. In a registration form you have the following fields: 'Period' in the mm / yyyy format 'Expiration Day' Concatenate the day with the period and parse for Date.

I need to handle the months with 29 for February and the months of 31 days. Putting 'Expiration Day' = 31, when it is February the parse plays for 03/01/2021 and in the months when it is not 31 the parse plays for the first day of the following month. I need that for these situations the parse takes the last day of the month and not the following month. I have already researched and did not see how to do it by parse itself.

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date dataDebito = df.parse(31 + "/" + 02 + "/" + 2021); //February is not 31 and I need you to parse it for 2/28/2021 or 2/29/2021 if it was a leap year.

I will present solutions for different Java versions.

Java 8 and later: java.time

I recommend that you use java.time, the modern Java date and time API, for your date work.

    DateTimeFormatter expirationParser = DateTimeFormatter.ofPattern("MM/uuuu");
     
    String expirationString = "02/2021";
    
    LocalDate expirationDay = YearMonth.parse(expirationString, expirationParser)
            .atEndOfMonth();

    System.out.println(expirationDay);

Output:

2021-02-28

Java 6 and 7: java.time through ThreeTen Backport

Code is the same as above. java.time has been backported to Java 6 and 7 in the ThreeTen Backport project. Link is at the bottom.

Java 1.5: Joda-Time

    DateTimeFormatter expirationParser = DateTimeFormat.forPattern("MM/yyyy");
    
    String expirationString = "02/2021";

    LocalDate expirationDay = YearMonth.parse(expirationString, expirationParser)
            .plusMonths(1) // following month
            .toLocalDate(1) // day 1 of month
            .minusDays(1); // last day of expiration month
    
    System.out.println(expirationDay);

2021-02-28

Java 1.1 through 1.4: Calendar

    DateFormat expirationFormat = new SimpleDateFormat("MM/yyyy");
    
    String expirationString = "02/2021";

    Date expirationMonth = expirationFormat.parse(expirationString);
    Calendar expirationCalendar = Calendar.getInstance();
    expirationCalendar.setTime(expirationMonth);
    expirationCalendar.add(Calendar.MONTH, 1); // 1st of following month
    expirationCalendar.add(Calendar.DATE, -1); // Last day of expiration month

    System.out.println(expirationCalendar.getTime());

Sun Feb 28 00:00:00 CET 2021

Links

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM