set to the last day of month - Android java.util

Android examples for java.util:Month

Description

set to the last day of month

Demo Code


//package com.java2s;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.Calendar;
import java.util.Date;
import static java.util.Calendar.DATE;

import static java.util.Calendar.MONTH;
import static java.util.Calendar.YEAR;

public class Main {
    /**//  w w  w .j  a va  2 s .  c om
     * set to the last day of month
     * @param calendar
     */
    public static void setToLastDay(Calendar calendar) {
        int year = getYear(calendar);
        int month = getMonth(calendar);
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.clear();
        calendar.set(year, month, maxDay);
        calendar.getTimeInMillis();
    }

    /**
     * @param date {@linkplain Date} to pull date information from
     *
     * @return a new Calendar instance with the date set to the provided date. Time set to zero.
     */
    public static Calendar getInstance(@Nullable Date date) {
        Calendar calendar = Calendar.getInstance();
        if (date != null) {
            calendar.setTime(date);
        }
        copyDateTo(calendar, calendar);
        return calendar;
    }

    /**
     * @return a new Calendar instance with the date set to today. Time set to zero.
     */
    public static @NonNull Calendar getInstance() {
        Calendar calendar = Calendar.getInstance();
        copyDateTo(calendar, calendar);
        return calendar;
    }

    public static int getYear(Calendar calendar) {
        return calendar.get(YEAR);
    }

    public static int getMonth(Calendar calendar) {
        return calendar.get(MONTH);
    }

    /**
     * Copy <i>only</i> date information to a new calendar.
     *
     * @param from calendar to copy from
     * @param to calendar to copy to
     */
    public static void copyDateTo(Calendar from, Calendar to) {
        int year = getYear(from);
        int month = getMonth(from);
        int day = getDay(from);
        to.clear();
        to.set(year, month, day);
        to.getTimeInMillis();
    }

    public static int getDay(Calendar calendar) {
        return calendar.get(DATE);
    }
}

Related Tutorials