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

前端 未结 6 2154
深忆病人
深忆病人 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:08

    Possibly a non-answer since you asked for a java.util.Date, but it seems like a good opportunity to point out that most work with dates and times and calendars in Java should probably be done with the Joda-Time library, in which case

    new LocalDate(year, month, 1)
    

    comes to mind.

    Joda-Time has a number of other nice things regarding days of the month. For example if you wanted to know the first day of the current month, you can write

    LocalDate firstOfThisMonth = new LocalDate().withDayOfMonth(1);
    

    In your comment you ask about passing a string to the java.util.Date constructor, for example:

    new Date("2012-09-19")
    

    This version of the constructor is deprecated, so don't use it. You should create a date formatter and call parse. This is good advice because you will probably have year and month as integer values, and will need to make a good string, properly padded and delimited and all that, which is incredibly hard to get right in all cases. For that reason use the date formatter which knows how to take care of all that stuff perfectly.

    Other earlier answers showed how to do this.

提交回复
热议问题