get Gap Count between first day of the Month and last day of the Month - Android java.util

Android examples for java.util:Month

Description

get Gap Count between first day of the Month and last day of the Month

Demo Code


//package com.java2s;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    public static int getGapCount() {
        Date startDate = null;/*from  ww w  . j  a  v  a 2 s .c o m*/
        Date endDate = null;
        try {
            startDate = sdf.parse(getFirstDayOfThisMonth());
            endDate = sdf.parse(getLastDayOfThisMonth());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(startDate);
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(endDate);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);

        return (int) ((toCalendar.getTime().getTime() - fromCalendar
                .getTime().getTime()) / (1000 * 60 * 60 * 24));
    }

    public static String getFirstDayOfThisMonth() {
        String str = "";
        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DATE, 1);//
        // lastDate.add(Calendar.MONTH,-1);//
        // lastDate.add(Calendar.DATE,-1);//

        str = sdf.format(lastDate.getTime());
        return str;
    }

    public static String getLastDayOfThisMonth() {
        String str = "";
        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DATE, 1);//
        lastDate.add(Calendar.MONTH, 1);//
        lastDate.add(Calendar.DATE, -1);//

        str = sdf.format(lastDate.getTime());
        return str;
    }
}

Related Tutorials