Java Month Day getFirstday_Month(Date date, int months)

Here you can find the source of getFirstday_Month(Date date, int months)

Description

get Firstda Month

License

Apache License

Declaration

public static Date getFirstday_Month(Date date, int months) throws ParseException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    public final static String webFormat = "yyyy-MM-dd";
    public final static String newFormat = "yyyy-MM-dd HH:mm:ss";

    public static Date getFirstday_Month(Date date, int months) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat(webFormat);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);//from w  w  w  . jav a 2s.c om
        calendar.add(Calendar.MONTH, months);
        Date theDate = calendar.getTime();

        GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
        gcLast.setTime(theDate);
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        String day_first = df.format(gcLast.getTime());
        StringBuffer str = new StringBuffer().append(day_first).append(" 00:00:00");
        day_first = str.toString();
        return parseDateNewFormat(day_first);
    }

    public static String format(Date date, String format) {
        if (date == null) {
            return null;
        }

        return new SimpleDateFormat(format).format(date);
    }

    public static Date parseDateNewFormat(String sDate) throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat(newFormat);
        Date d = dateFormat.parse(sDate);
        return d;
    }
}

Related

  1. getDaysOfMonth(Date date)
  2. getDaysOfMonth(Date date)
  3. getFirstDate(String base_month)
  4. getFirstDateOfCurMonth()
  5. getFirstDateOfMonth(Date theDate)
  6. getFirstDayOfCurMonth()
  7. getFirstDayOfCurrentMonth()
  8. getFirstDayOfLastMonth()
  9. getfirstDayOfMonth()