How to generate a Date from just Month and Year in Java?

前端 未结 6 2247
深忆病人
深忆病人 2021-02-12 11:30

I need to generate a new Date object for credit card expiration date, I only have a month and a year, how can I generate a Date based on those two? I need the easiest way possib

6条回答
  •  不要未来只要你来
    2021-02-12 12:17

    java.time

    Using java.time framework built into Java 8

    import java.time.YearMonth;
    
    int year = 2015;
    int month = 12;
    YearMonth.of(year,month); // 2015-12
    

    from String

    YearMonth.parse("2015-12"); // 2015-12
    

    with custom DateTimeFormatter

    import java.time.format.DateTimeFormatter;
    
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM yyyy");
    YearMonth.parse("12 2015", formatter); // 2015-12
    

    Conversions To convert YearMonth to more standard date representation which is LocalDate.

    LocalDate startMonth = date.atDay(1); //2015-12-01
    LocalDate endMonth = date.atEndOfMonth(); //2015-12-31
    

提交回复
热议问题