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

前端 未结 6 2150
深忆病人
深忆病人 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.

    0 讨论(0)
  • 2021-02-12 12:12

    The most common sense approach would be to use the Date("YYYY-MM-DD") constructor even though it is deprecated. This is the easiest way to create a date on the fly. Screw whoever decided to deprecate it. Long live Date("YYYY-MM-DD")!!!

    0 讨论(0)
  • 2021-02-12 12:12

    Don’t use this answer. Use the answers by Przemek and Ray Toel. As Przemek says, prefer to use a YearMonth for representing year and month. As both say, if you must use a date, use LocalDate, it’s a date without time of day.

    If you absolutely indispensably need an old-fashioned java.util.Date object for a legacy API that you cannot change, here’s one easy way to get one. It may not work as desired, it may not give you exactly the date that you need, it depends on your exact requirements.

        YearMonth expiration = YearMonth.of(2021, 8); // or .of(2021, Month.AUGUST);
        Date oldFashionedDateObject = Date.from(expiration
                .atDay(1)
                .atStartOfDay(ZoneId.systemDefault())
                .toInstant());
        System.out.println(oldFashionedDateObject);
    

    On my computer this prints

    Sun Aug 01 00:00:00 CEST 2021
    

    What we got is the first of the month at midnight in my local time zone — more precisely, my JVM’s time zone setting. This is one good guess at what your legacy API expects, but it is also dangerous. The JVM’s time zone setting may be changed under our feet by other parts of the program or by other programs running in the same JVM. In other words, we cannot really be sure what we get.

    The time zone issue gets even worse if the date is transmitted to a computer running a different time zone, like from client to server or vice versa, or to a database running its own time zone. There’s about 50 % risk that your Date will come through as a time in the previous month.

    If you know the time zone required in the end, it will help to specify for example ZoneId.of("America/New_York") instead of the system default in the above snippet.

    If your API is lenient and just needs some point within the correct month, you’ll be better off giving it the 2nd of the month UTC or the 3rd of the month in your own time zone. Here’s how to do the former:

        Date oldFashionedDateObject = Date.from(expiration
                .atDay(2)
                .atStartOfDay(ZoneOffset.UTC)
                .toInstant());
    
    0 讨论(0)
  • 2021-02-12 12:14

    Like

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
    Date utilDate = formatter.parse(year + "/" + month);
    

    Copied from Create a java.util.Date Object from a Year, Month, Day Forma or maybe like

    DateTime aDate = new DateTime(year, month, 1, 0, 0, 0);
    

    Copied from What's the Right Way to Create a Date in Java?

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-12 12:19

    You could use java.util.Calendar:

    Calendar calendar = Calendar.getInstance();
    calendar.clear();
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.YEAR, year);
    Date date = calendar.getTime();
    
    0 讨论(0)
提交回复
热议问题