Java Month of Year create(int year, int month, int day)

Here you can find the source of create(int year, int month, int day)

Description

Create a (truncated) date object from year, month, day.

License

Open Source License

Parameter

Parameter Description
year Year, for example 2014
month Month, for example 2 for February
day Day, for example 31st (of December)

Return

truncated date (without hours, minutes, seconds and others)

Declaration

public static Date create(int year, int month, int day) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Calendar;
import java.util.Date;

public class Main {
    /**//  w  w w.  j ava  2  s  .co  m
     * Create a (truncated) date object from year, month, day.
     * Throws IllegalArgumentException if the parameters don't form
     * a valid date, for example 2014, 2, 31 or 2014, 99, 99
     *
     * @param year  Year, for example 2014
     * @param month Month, for example 2 for February
     * @param day   Day, for example 31st (of December)
     * @return truncated date (without hours, minutes, seconds and others)
     */
    public static Date create(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);

        validate(year, month, day, calendar);

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }

    private static void validate(int year, int month, int day, Calendar calendar) {
        if (calendar.get(Calendar.DAY_OF_MONTH) != day) {
            throw new IllegalArgumentException(
                    String.format("Invalid day=%s for year=%s and month=%s", day, year, month));
        }
        if (calendar.get(Calendar.MONTH) != month - 1) {
            throw new IllegalArgumentException(
                    String.format("Invalid month=%s for year=%s and day=%s", month, year, day));
        }
    }
}

Related

  1. create(final int year, final int month, final int day)
  2. create(int year, int month, int day, int hour, int minute, int second)
  3. createKey(int instance, int year, int month, int day, int hour, int min, int sec, int milli, String uuid, boolean rolling)
  4. createTimestamp(int year, int month, int day, int hour, int minutes, int seconds)
  5. currentYearMonth()